r/PHPhelp • u/bkdotcom • Dec 10 '16
simple array reference (&) confusion
Can someone explain this to me?
I figured it out, but it might be helpful / refresher for others.
$myArray = array(
'sub' => array( 'foo' => 'bar' ),
);
$sub = &$myArray['sub']; // this is the only assignment by reference
// both sides become references.. not to each other, but to the value
$copy = $myArray;
$copy['sub']['foo'] = 'WTF';
var_dump($myArray);Why do $myArray['sub'] and $copy['sub'] point to the same place?
ie, why does the above output array(1) { ["sub"]=> &array(1) { ["foo"]=> string(3) "WTF" } }
The relevant PHP documentation: What references do:
Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments.
I can't believe I've never run into this "issue" before / can't believe my understanding of php references has been so flawed..
by assigning by reference $sub = &$myArray['sub'], both sides of the operator become references, not to each other, but to "location c", where the value is actually stored)
That reference gets copied when the array is copied.
SHAZBOT