<?php$arr = Array (' 1 ', ' 2 '), foreach ($arr as & $value) {}foreach ($arr as $value) { var_dump ($value);}
Output
string(1) "1"string(1) "1"
Let's just say it, put it foreach
into an assignment.
foreach($arr as &$value) { //noop}
is roughly
#begin first foreach$value = &$arr[0];//noop$value = &$arr[1];//noop#end foreach
If you print $arr, you will see
array(2) { [0]=> string(1) "1" [1]=> &string(1) "2"}
$value
that is, still $arr[1]
the reference (alias)
And then we'll take the second foreach apart.
#begin second foreach$value = $arr[0];//note: 由于$value <=> &$arr[1], 此时$arr[1]被赋值成为$arr[0],也就是1var_dump($value);//1$value = $arr[1];//相当于$arr[1] = $arr[1]; 没有实际效果var_dump($value);//1#end foreach
The solution is never to use &
Or honestly follow the official website's instructions, use unset to dereference
<?php $arr = array (1, 2, 3, 4); $arr as & $value) { $value = $value * 2;} //$arr is now Array (2, 4, 6, 8) unset ( $value); //break the reference and the last Element?> span>
PHP array foreach reference problem