Wednesday, February 17, 2010

PHP: References To Array Elements Are Risky

References to array elements can bite! And it is not only the case with referencing in foreach loop. It seems that creating a reference to an array element replaces that element itself with a reference. If you then copy such an array and change the elements inside copy you can overwrite original value!

All of the presented code was tested on Mac (PHP 5.2.11), Linux (PHP 5.2.6-1+lenny4) and Windows XP (PHP 5.3.0) using PHP cross platform testing lab on Mac based on VirtualBox.

Changing copy affects original array

Sounds impossible? I agree. I couldn't believe it myself. Nevertheless here is the proof:
Example 1
$a = array('one', 'two', 'three', 'four'); 
$a2 = &$a[2]; 
 
$b = $a; 
$b[1] = 'two again'; 
$b[2] = 'reference bites'; 
 
var_dump($a, $b);
The above example will output:
array(4) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  &string(15) "reference bites"
  [3]=>
  string(4) "four"
}
array(4) {
  [0]=>
  string(3) "one"
  [1]=>
  string(9) "two again"
  [2]=>
  &string(15) "reference bites"
  [3]=>
  string(4) "four"
}

Changing copy of a copy affects original array too

If you look at the dump carefully you will see that $a[2] and $b[2] are displayed as references here. That would mean the element has been replaced with a reference. And if you copy a reference you just get what? Same reference, right? So any copy of $a would contain that reference. Going forward any copy of a copy of $a would contain that same reference. Let's check it:
Example 2
$a = array('one', 'two', 'three', 'four'); 
$a2 = &$a[2]; 
 
$b = $a; 
$c = $b; 
$c[2] = 'references bites more'; 
$b[1] = 'two again'; 
$a[0] = 'one more'; 
var_dump($a, $b, $c);
The above example will output:
array(4) {
  [0]=>
  string(8) "one more"
  [1]=>
  string(3) "two"
  [2]=>
  &string(21) "references bites more"
  [3]=>
  string(4) "four"
}
array(4) {
  [0]=>
  string(3) "one"
  [1]=>
  string(9) "two again"
  [2]=>
  &string(21) "references bites more"
  [3]=>
  string(4) "four"
}
array(4) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  &string(21) "references bites more"
  [3]=>
  string(4) "four"
}

Tricky "foreach" with reference explained

As you can see, the only element affected is the one referenced. That can lead to serious potential problems. Working on a copy of an array with scalar elements seems to be not as safe as one may thought. However, that explains one of the biggest pitfalls of iterating arrays in PHP: foreach with reference. The following is rather common knowledge:
Example 3
$a = array('one', 'two', 'three', 'four'); 
foreach ($a as &$v) {} 
foreach ($a as $v) {} 
var_dump($a);
The above example will output:
array(4) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  &string(5) "three"
}
But what was the explanation for that, again? It is quite clear that $v keeps reference to $a[3] after the foreach loop is finished. So what values does $v (effectively $a[3]) get within the next foreach loop? Let's see:
Example 4
$a = array('one', 'two', 'three', 'four'); 
foreach ($a as &$v) {} 
foreach ($a as $v) { 
 var_dump($a[3]); 
}
The above example will output:
string(3) "one"
string(3) "two"
string(5) "three"
string(5) "three"
Well, it's quite obvious. Or is it? As the foreach manual page states: "unless the array is referenced, foreach operates on a copy of the specified array and not the array itself". I would assume that "array is referenced" means array elements are referenced like this: foreach ($a as &$v) {} Apparently that is not the case with the second loop and it should work on a copy. Let's have a look what exactly would happen if the second foreach loop really worked on a solid copy:
Example 5
$a = array('one', 'two', 'three', 'four'); 
$b = $a; 
foreach ($a as &$v) {} 
foreach ($b as $v) {} 
var_dump($a);
The above example will output:
array(4) {
  [0]=>
  string(3) "one"
  [1]=>
  string(3) "two"
  [2]=>
  string(5) "three"
  [3]=>
  &string(4) "four"
}
I imagine you did expect this result. Beware references to array elements and thanks for reading. I hope you found this article useful. Please don't think twice before you leave your comment.

145 comments:

  1. Using the latest version of PHP, instead of in example 5 doing the $b = $a, I instead was able to work around the issue by changing the $v in the second foreach loop to a different variable. It seems that using the same value variable that you used as the reference variable is what is not working as expected.

    ReplyDelete
  2. Another interesting bit: If you reference an array element that is later unset() or popped, the reference will retain its value;

    $a = array(1,2,3,4);
    $b = &$a[2]; // b = 3

    unset($a[2]);

    print $b; // prints 3

    ReplyDelete
  3. The reference to array element is really confusing me. I am still not very clear if that is a bug of PHP. And if the bug has been solved? Because only less article talked about it.

    If we unset (all) the reference to array element except itself, the array element would come back to normal. This is weird. Don't know the how it implemented

    ';

    unset($b);
    unset($c);

    var_dump($a);
    echo '
    ';


    output:
    array(2) { [0]=> &int(10) [1]=> int(1) }
    array(2) { [0]=> int(10) [1]=> int(1) }

    ReplyDelete
  4. I think the "Tricky "foreach" with reference explained" part is a misunderstanding. The point is not whether the second loop operates on the original array or a copy -- it doesn't change the array, so original-or-copy doesn't matter.

    The point is that the second loop comes after the first loop, and specifically after the symbol "v" has been bound to the last array element. Try renaming the loop variable in the second loop and it will go away. The second loop doesn't use a local variable as the loop variable, it actually uses the last array cell as the loop variable, because the name "v" is still bound to it. Unsetting "v" after the first loop is another way to make it go away, and actually I recommend to *always* unset the loop variable after a "foreach with reference" so you don't acidentally trip over this.

    ReplyDelete
  5. WRT your first observation, the PHP manual says that "references do not work like C pointers and more like Unix hardlinks". Actually, they work like neither of the two.

    Very good source: http://derickrethans.nl/talks/phparch-php-variables-article.pdf

    PHP has two kinds of variables, and a variable can switch between the two:

    - non-reference variables. New variables are created like this. Assigning them to another variable by value increases an internal reference count, it doesn't actually copy the value. Write access copies the variable if the refcount is >1, otherwise it modifies the variable. Assigning the variable to another variable by reference is treated as write access; this makes sure that the implicit reference in by-value assignment doesn't become explicit, but it also is the kind of "assignment affects the source" behavior you described. Yes, it affects the source -- it is a write access that triggers copy-on-write AND it turns the source variable into a reference variable.

    - reference variables. There are at least two names for this variable, and they are explicit references, i.e. no copy-on-write. If the refcount drops to 1, the variable becomes a non-reference variable again. The latter effect makes unset() cancel the effect in your example.

    ReplyDelete
  6. A final piece of information (sorry for multi-posting, but I'm writing this while discovering it myself):

    When an array is actually copied (for example, when a non-reference -- i.e. copy-on-write -- array with a refcount >1 is modified), then its element variables are treated in a way that is neither "assignment by value" nor "assignment by reference". Instead, the new array just uses the same variables as the original, and the refcount of each variable is increased by one. (In contrast: Assignment by value would copy reference variable elements, while assignment by reference would copy non-reference variable elements with a refcount >1, so this behavior is neither of the two).

    This also explains a more common observation made about arrays: That assigning arrays by value seemingly copies "normal" (non-reference) elements (actually it does copy-on-write), and shares elements that are references to other variables. Your observation is new in that sharing is also triggered by making a reference to a "normal" element, since it turns it into a reference variable.

    ReplyDelete
  7. can somebody post this issue on stackoverflow.com?? i wanna hear what community will say about this

    ReplyDelete
  8. I wish to show thanks to you just for bailing me out of this particular trouble.As a result of checking through the net and meeting techniques that were not productive, I thought my life was done
    Python training in Bangalore
    Python online training
    Python Training in Chennai

    ReplyDelete
  9. Attend The Python Training in Hyderabad From ExcelR. Practical Python Training Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Hyderabad.
    python training in bangalore

    ReplyDelete
  10. Hi, It’s Amazing to see your blog.This provide us all the necessary information regarding
    upcoming real estate project which having all the today’s facilities.
    autocad in bhopal
    3ds max classes in bhopal
    CPCT Coaching in Bhopal
    java coaching in bhopal
    Autocad classes in bhopal
    Catia coaching in bhopal

    ReplyDelete
  11. very interesting blog, Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man, I’ll be waiting for your next post.
    ExcelR Solutions

    ReplyDelete
  12. In this modern era, Data Analytics provides a business analytics course with placement subtle way to analyse the data in a qualitative and quantitative manner to draw logical conclusions. Gone are the days where one has to think about gathering the data and saving the data to form the clusters. For the next few years, it’s all about Data Analytics and it’s techniques to boost the modern era technologies such as Machine learning and Artificial Intelligence.

    ReplyDelete
  13. Are you looking for the best home elevators manufacturers in Chennai, click here the link below to know more. Home elevator india | lift for home

    ReplyDelete
  14. Thanks for sharing it.I got Very significant data from your blog.your post is actually Informatve .I'm happy with the data that you provide.thanks

    click here
    see more
    visit us
    website
    more details

    ReplyDelete
  15. Thanks for your excellent blog and giving great kind of information. So useful. Nice work keep it up thanks for sharing the knowledge.
    Visit us
    Click Here
    For More Details
    Visit Website
    See More

    ReplyDelete
  16. Click to learn more about Python training in Bangalore:- Python training in bangalore

    ReplyDelete
  17. blockchain online training
    Nice article, interesting to read…
    Thanks for sharing the useful information

    ReplyDelete
  18. Thank you for valuable information.I am privilaged to read this post.aws training in bangalore

    ReplyDelete
  19. Your articles really impressed for me,because of all information so nice.python training in bangalore

    ReplyDelete
  20. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!
    Please check ExcelR Data Science Courses

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. Nice blog! Such a good information about data analytics and its future..
    Good post! I must say thanks for the information.
    data analytics course L
    Data analytics Interview Questions

    ReplyDelete
  23. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    data analytics cours mumbai

    data science interview questions

    business analytics course

    ReplyDelete
  24. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck... Thank you!!! data analytics courses

    ReplyDelete
  25. Hello there! I just want to offer you a big thumbs up for your great info you have right here on this post.
    I'll be coming back to your web site for more soon.
    Click here to technology.

    ReplyDelete
  26. Awesome blog, I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the
    good work!.business analytics certification

    ReplyDelete
  27. article from a very amazing blog, Good Job, Thank you for presenting a wide variety of information that is very interesting to see.
    Home elevators
    Home elevators Melbourne
    Home lifts

    ReplyDelete
  28. can somebody post this issue on stackoverflow.com?? i wanna hear what community will say about this
    accent pillow case baby canvas
    accent pillow case baby canvas
    accent pillow case housewares

    ReplyDelete
  29. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    Python Training
    Digital Marketing Training
    AWS Training

    ReplyDelete
  30. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here...data analytics courses

    ReplyDelete
  31. Hi, This is your awesome article , I appreciate your effort, thanks for sharing us.
    cism training
    cism certification

    cisa training,
    cisa certification
    cisa exam

    ReplyDelete
  32. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work....machine learning courses in bangalore

    ReplyDelete
  33. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work....artificial intelligence course

    ReplyDelete
  34. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.Keep update more information.

    aws training in chennai | aws training in annanagar | aws training in omr | aws training in porur | aws training in tambaram | aws training in velachery


    ReplyDelete
  35. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.....machine learning courses in bangalore

    ReplyDelete
  36. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.
    AWS training in chennai | AWS training in anna nagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  37. Thanks for sharing this informations
    Java training in coimbatore
    CCNA Training Institute in Coimbatore
    Selenium Training in Coimbatore
    python training institute in coimbatore
    python course in coimbatore
    artificial intelligence training in coimbatore
    DevOps Training institute in coimbatore

    ReplyDelete
  38. I like viewing web sites which comprehend the price of delivering the excellent useful resource free of charge. I truly adored reading your posting. Thank you!...artificial intelligence course

    ReplyDelete
  39. I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more....artificial intelligence course in bangalore

    ReplyDelete
  40. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    data analytics courses

    ReplyDelete
  41. it is different from what was committed to memory, thus allowing a memory overwrite. artificial intelligence courses in hyderabad

    ReplyDelete

  42. Lockdown is running in the whole country due to coronavirus, in such an environment we are committed to provide the best solutions for QuickBooks Support Phone Number.
    Contact QuickBooks Customer Service Phone Number to get in touch.
    Dial QuickBooks Toll free Number : 1-844-908-0801

    ReplyDelete
  43. Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

    Forex Signals Forex Strategies Forex Indicators Forex News Forex World

    ReplyDelete
  44. It was not first article by this author as I always found him as a talented author. Perry Mason Leather Jacket

    ReplyDelete
  45. Thanks for sharing great information. I likes your work. Really it was awesome article. They are read so interesting.

    Fashion bloggers in India

    ReplyDelete
  46. This was an extremely wonderful post. Thanks for providing this info.
    Longmire Coat

    ReplyDelete
  47. I read your blog and i found it very interesting and useful blog for me. I hope you will post more like this, i am very thankful to you for these type of post.
    Rajasthan Budget Tours

    ReplyDelete
  48. Such a very useful information! Thanks for sharing this useful information with us. Really great effort. Fashion bloggers in India

    ReplyDelete
  49. I really enjoyed reading your article. I found this as an informative and interesting post, so I think it is very useful and knowledgeable. Fashion bloggers in India

    ReplyDelete
  50. I am a new user of this site so here i saw multiple articles and posts posted by this site,I curious more interest in some of them hope you will give more information on this topics in your next articles.
    artificial intelligence course

    ReplyDelete
  51. Nice Blog !
    Here We are Specialist in Manufacturing of Movies, Gaming, Casual, Faux Leather Jackets, Coats And Vests See Mr Robot Jacket

    ReplyDelete
  52. I have been searching to find a comfort or effective procedure to complete this process and I think this is the most suitable way to do it effectively. ExcelR Data Science Course In Pune

    ReplyDelete
  53. Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work!Business Analytics Courses

    ReplyDelete
  54. Hi there, I found your blog via Google while searching for such kinda informative post and your post looks very interesting for me ExcelR Data Analytics Courses

    ReplyDelete

  55. ExcelR provides Business Analytics Courses. It is a great platform for those who want to learn and become a Business Analytics. Students are tutored by professionals who have a degree in a particular topic. It is a great opportunity to learn and grow.

    Business Analytics Courses

    ReplyDelete
  56. Thanks for posting this info. I just want to let you know that I just check out your site. Qbook

    ReplyDelete
  57. ExcelR provides Business Analytics Course. It is a great platform for those who want to learn and become a Business Analytics Courses. Students are tutored by professionals who have a degree in a particular topic. It is a great opportunity to learn and grow.

    Business Analytics Courses

    ReplyDelete
  58. aws training in chennai - AWS Amazon web services is a Trending Technologies and one of the most sought after courses.Join the Best Aws course in Chennai now.

    IOT training in chennai - Internet of things is one of best technology, Imagine a world with a Internet and everything minute things connected to it .

    DevOps Training Institute in Chennai - Just from DevOps course Best DeVops training Institute in Chennai is also providing Interview Q & A with complete course guidance, Join the Best DevOps Training Institute in Chennai.

    Load runner training in Chennai - Load runner is an software testin tool. It is basically used to test application measuring system behaviour and performance under load. Here comes an Opportunity to learn Load Runner under the guidance of Best Load Runner Training Institute in Chennai.

    apache Spark training in Chennai - Apache Spark is an open- source, Split Processing System commonly used for big data workloads. Learn this wonderful technology from and under the guidance of Best Apache spark Training Institute in Chennai.

    mongodb training in chennai - MongoDB is a cross platform document - oriented database Program. It is also classified as NO sql database Program. Join the Best Mongo DB Training Institute in Chennai now.

    ReplyDelete
  59. Here at this site really the fastidious material collection so that everybody can enjoy a lot. ExcelR Data Scientist Course In Pune

    ReplyDelete
  60. The AWS certification course has become the need of the hour for freshers, IT professionals, or young entrepreneurs. AWS is one of the largest global cloud platforms that aids in hosting and managing company services on the internet. It was conceived in the year 2006 to service the clients in the best way possible by offering customized IT infrastructure. Due to its robustness, Digital Nest added AWS training in Hyderabad under the umbrella of other courses

    ReplyDelete
  61. This is an informative post. Got a lot of info and details from here. Thank you for sharing this and looking forward to reading more of your post.
    on demand app solutions

    ReplyDelete
  62. I was basically inspecting through the web filtering for certain data and ran over your blog. I am flabbergasted by the data that you have on this blog. It shows how well you welcome this subject. Bookmarked this page, will return for extra. 360digitmg.com/india/data-science-using-python-and-r-programming-in-jaipur">data science course in jaipur</a

    ReplyDelete
  63. Thanks for sharing on References To Array Elements Are Risky. Informative blog

    Data Science Training in Pune

    ReplyDelete
  64. AWS certification is a degree of cloud competence obtained by an IT professional after clearing one or more of the public cloud provider's tests. AWS certifications allow IT professionals to demonstrate and certify their technical cloud knowledge and skills. Aws course in chennai

    ReplyDelete
  65. I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you made in writing this article. Bane Coat

    ReplyDelete
  66. Our share market trading focus on investing and fundamentals, Choose us for the best share market training classes in Chennai. Enroll for the
    best Courses in Chennai

    ReplyDelete
  67. Awesome blog. Thanks for sharing this blog. Keep update like this...
    Android Training in Bangalore
    Android Classes in Pune

    ReplyDelete
  68. Pleasant data, important and incredible structure, as offer great stuff with smart thoughts and ideas, loads of extraordinary data and motivation, the two of which I need, because of offer such an accommodating data here.
    data analytics course in hyderabad

    ReplyDelete

  69. I like your post. I appreciate your blogs because they are really good. Please go to this website for Data Science course in Bangalore. These courses are wonderful for professionals.

    ReplyDelete
  70. I wish to show thanks to you just for bailing me out of this particular
    trouble.As a result of checking through the net and meeting
    .

    ReplyDelete
  71. A good article with useful information. Thank you for sharing.
    power bi training institutes in Hyderabad

    ReplyDelete
  72. "Wow, this is really eye-opening! Thanks for sharing this crucial insight about PHP and array references. It's a great reminder to be cautious when working with arrays. 👏"
    Data Analytics Courses In Bangalore

    ReplyDelete
  73. This article provides a crucial warning about the potential pitfalls of referencing array elements in PHP. The examples effectively demonstrate how references can affect data integrity, offering valuable insights for PHP developers. Thank you for sharing your knowledge.
    Data Analytics Courses in Nashik

    ReplyDelete
  74. This article likely highlights the potential risks associated with using references to array elements in PHP, emphasizing the importance of careful coding practices for safe and reliable programming.

    Data Analytics Courses In Kochi



    ReplyDelete
  75. This article probably emphasises the potential dangers of utilising array references in PHP, highlighting the value of cautious coding techniques for secure and dependable programming.
    Data Analytics Courses in Agra

    ReplyDelete
  76. Your article contributes to raising awareness about this topic and provides practical advice on how to mitigate these risks. Thank you for sharing this information.
    Data Analytics Courses In Chennai

    ReplyDelete
  77. nice blog
    Data Analytics Courses In Vadodara

    ReplyDelete
  78. Referencing PHP array elements can be risky if not done with caution, as improper handling can lead to unexpected results or security vulnerabilities.
    In the field of data analytics, Glasgow offers comprehensive Data Analytics courses, ensuring professionals are well-equipped to handle data effectively and securely. Please also read Data Analytics courses in Glasgow.

    ReplyDelete
  79. This article is a goldmine of information. Thanks for the insights

    ReplyDelete
  80. I learned so much from this post. It's like a mini-education in the subject matter.

    ReplyDelete
  81. was looking for this for few days, thanks for sharing. very helpful.
    financial modelling course in melbourne

    ReplyDelete
  82. "I've encountered issues with referencing array elements in PHP before. It seems convenient at first, but the potential risks, like unexpected side effects, can lead to hard-to-debug problems. It's crucial to weigh the benefits against the potential pitfalls when deciding whether to use references in array manipulation."
    Best Data analytics courses in India

    ReplyDelete
  83. Referencing array elements directly in PHP can introduce potential risks, causing unintended side effects during manipulation or assignment. Modifications to array elements via references might lead to unexpected changes across multiple variables or functions, challenging code predictability. Caution is advised to mitigate the complexities and maintain code clarity when utilizing array element references in PHP.
    Data Analytics courses in new york

    ReplyDelete
  84. Hey there! It's interesting to learn about the potential risks associated with referencing array elements in PHP. Understanding these risks can help developers write safer and more reliable code. It's always important to be aware of any potential pitfalls when working with programming languages. Thanks for sharing this valuable insight!
    Data analytics courses in Rohini

    ReplyDelete
  85. Indeed a great article! I am definitely going to bookmark it to go through it over again after work.
    SAP training in Mumbai
    SAP live project in Mumbai
    SAP course in Mumbai

    ReplyDelete