I was messing with arrays and references, when I came across an interesting problem. Take this code, for example:
// Set everything up
$testArray = array(
'a' => array(),
'b' => array()
);
$saved = array();
$ref =& $testArray['b'];
// Set a value via the reference
$ref = array(1);
// Save the current array state
$saved[] = $testArray; // This shouldn't be a reference, right?
// Set another value via the reference
$ref = array(2);
// Save the current array state
$saved[] = $testArray; // This shouldn't be a reference, right?
Nothing too complicated. It makes an array, and a reference to a "deep value" in the array.
When I var_dump($saved)
, the result is not what I expect! I get:
array(2) {
[0]=>
array(2) {
["a"]=>
array(0) {
}
["b"]=>
&array(1) {
[0]=>
int(2)
}
}
[1]=>
array(2) {
["a"]=>
array(0) {
}
["b"]=>
&array(1) {
[0]=>
int(2)
}
}
}
I thought arrays were copied by value, not reference. Why is [b]
equal to array(2)
in both spots? How can I copy an array and break its references?
I want the result to be:
array(2) {
[0]=>
array(2) {
["a"]=>
array(0) {
}
["b"]=>
array(1) {
[0]=>
int(1)
}
}
[1]=>
array(2) {
["a"]=>
array(0) {
}
["b"]=>
array(1) {
[0]=>
int(2)
}
}
}
Why is $ref
still linked to a copy of the $testArray
array? I want to basically save the "state" of the array, and have the reference only update the original and not the copy.