Let's explain this.foreachExpand to assign values
foreach($arr as &$value) { //noop}
Roughly
php#begin first foreach$value = &$arr[0];//noop$value = &$arr[1];//noop#end foreach
At this time, if you print $ arr, you will see
array(2) { [0]=> string(1) "1" [1]=> &string(1) "2"}
That is to say$valueStill yes$arr[1](Alias)
Then we split the second foreach.
php# Begin second foreach $ value = $ arr [0]; // note: Due to $ value <=> & $ arr [1], $ arr [1] is assigned $ arr [0], that is, 1var_dump ($ value); // 1 $ value = $ arr [1]; // equivalent to $ arr [1] = $ arr [1]; no actual effect var_dump ($ value); // 1 # end foreach
The solution is never used &
Or use unset to release the reference according to instructions on the official website.
$ Value and $ arr [1] point to the same memory space. The second loop actually changes the value of $ arr [1] for each loop.
After learning, let's simply look at the above answer.
After the first foreach ends, $ value = & $ arr [1]. Note that this is a reference, which can be understood as a pointer.
Focus on the second foreach:
The first time is & $ arr [1] = $ arr [0]. This isAssignment operationAt this time, $ arr [1]The value has been modified.It is $ arr [0], that is, 1. Now $ arr = ['0' => 1, '1' => 1].
The second time & $ arr [1] = $ arr [1], same as above. Final $ arr = ['0' => 1, '1' => 1].