In the PHP, we have a copy-on-write behavior.
- Why the following code has an unexpected result? As you can see
passByValue
function mutate the $value array. Since it's a pass by value, I expect that it must not change the original array passed, Actually is pushes new element in the original array too! - What are the differences between
$x = &$a['x'];
and$x =& $a['x'];
<?php
function passByValue($value){
$value['x'][] = 2;
}
$a =['x'=>[[1]]];
$x = &$a['x']; // Comment this line, the array is not mutated
passByValue($a);
var_dump($a);
?>
array(1) {
["x"]=>
&array(2) {
[0]=>
array(1) {
[0]=>
int(1)
}
[1]=>
int(2)
}
}