AlexV
10-16-2009, 06: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!
Alexandre.
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!
Alexandre.