In order to lead the problem, first look at the following piece of code:
<?php $arr = [ 'a', 'b', 'c', 'd', ]; foreach ($arr as &$each){ echo $each; } echo PHP_EOL; foreach ($arr as $each){ echo $each; }
This code is very simple, two elements of the output array will feel sorry abcd output twice, the following output?:
I am not feeling very strange? I did not give array assignment ah, the last element of the array how it changed when the second cycle?
problem analysis
Let's look below for some nice amend the code:
<?php $arr = [ 'a', 'b', 'c', 'd', ]; foreach ($arr as &$each){ echo $each; } echo PHP_EOL; $each = '1'; var_dump($arr);
It is not found?
Modify each variable will modify the last element of arr, this is why?
Have had experience using C language is probably one can understand how it happens.
A close look at the above foreach loop, each variable using the & symbol, this symbol comparable to the address-c
php's foreach will at each cycle, say the current element is assigned to each, and then enter the body of the loop
When the last element foreach traversal is completed, each variable is not released but points to the last element in the array arr, so when assigned to each in the back, in fact, change when the array arr
This, the process has been understood, the following reduction at the beginning of the process twice foreach:
After the completion of the first foreach, obviously, each pointing to the last element of the array, the following entered the second foreach:
-
The first time through, the arr [0] is assigned to each, equivalent arr [3] = arr [0], arr case is: [ 'a', 'b', 'c', 'a']
-
The second pass, the arr [. 1] is assigned to each, equivalent arr [3] = arr [1], for the case arr: [ 'a', 'b', 'c', 'b']
-
The third pass, the arr [2] is assigned to each, equivalent arr [3] = arr [2], this time to arr: [ 'a', 'b', 'c', 'c']
-
Fourth traversal, the arr [. 3] is assigned to each, equivalent arr [3] = arr [3], as the case arr: [ 'a', 'b', 'c', 'c']
The results of the analysis and results output before the same, each change we will print out the second foreach code is as follows:
<?php $arr = [ 'a', 'b', 'c', 'd', ]; foreach ($arr as &$each){ } foreach ($arr as $each){ var_dump($arr); }
Screenshot results as follows:
Fully consistent with the results of the analysis we, at this point, the end
php version I used was: 7.2