Found an error-prone, but do not understand the principle of the explanation does not understand the problem, encounter similar problems of friends can refer to.
Copy the Code code as follows:
foreach ($array as & $v) {
$v = explode ('/', $v);
}
foreach ($array as $v) {
Do something
}
In this case, in the second loop there will be a logic error, adding the second loop where do something is the output $v, the output of the loop to the last is the penultimate element, not the last
To write like this.
Copy the Code code as follows:
foreach ($array as & $v) {
$v = explode ('/', $v);
}
Unset ($v);
foreach ($array as $v) {
Do something
}
Or the first cycle of this.
Copy the Code code as follows:
foreach ($array as $k = = $v) {
$array [$k] = explode ('/', $r);
}
Say the principle.
The first loop uses the reference, and after the loop is finished, $v refers to the last element of the $array array, and when the second loop is started, the $v variable is assigned a new value each time the loop is called, and in PHP, if a memory space is referenced, the value of the memory space is changed directly when it is changed. , that is, when the first loop of the second foreach, the value of the last element of the $array is changed to the value of the first element of the $array, when the second loop is changed to the value of the second element, when the second cycle is reversed, it is changed to the second value of the penultimate element, And the last time you loop, the value of enlightenment must be the second-lowest value.
Of course, if PHP's for loop has scope, this problem does not occur .....
This article is from the "Half City" blog, please be sure to keep this source http://vabc1314.blog.51cto.com/2164199/1663122
Where to use references in a foreach loop in PHP