View Full Version : PHP arrays and reference operator (&) bug (?)

10-16-2009, 07:55 PM
See the following simple code snippet...

You have a source array, then you use some reference operator on that array (pretty useless in this snippet, but can happen in real world case like a "foreach ($source as &$currSource)") then you copy (duplicate) the array in another variable. Then you modify the content of the copy and the original is modified too!

I don't understand why. Seems like a PHP bug to me or a misunderstanding of PHP references on my side.

$source = array('apple', 'banana', 'strawberry');

$dummy = &$source[1]; /* If you use a reference operator (&) on an array,
any modification on a COPY of that array will also modify the ORIGINAL array! */

$copySource = $source;
$copySource[1] = 'orange';

print_r($source); /* Output Array ( [0] => apple [1] => orange [2] => strawberry )! Why? */

Thank you!


10-16-2009, 10:18 PM
Found out the solution myself... This is indeed a very old bug in PHP still present in 5.3.0 (and will probably be there a wile).

Due to peculiarities of the internal workings of PHP, if a reference is made to a single element of an array and then the array is copied, whether by assignment or when passed by value in a function call, the reference is copied as part of the array. This means that changes to any such elements in either array will be duplicated in the other array (and in the other references), even if the arrays have different scopes (e.g. one is an argument inside a function and the other is global)! Elements that did not have references at the time of the copy, as well as references assigned to those other elements after the copy of the array, will behave normally (i.e. independent of the other array).


This will not be fixed anytime soon. It is a deep seated problem in the implementation and fixing it would cause speed problems and numerous other problems, This is somthing that can be coded around too so should not cause massive problems.