Copy CodeThe code is as follows:
$a = Array (1, 2);
$b = Array (11, 12);
foreach ($a as & $r) {
}
foreach ($b as $r) {
}
echo $a [1]; Output 12
The original meaning of the two loops may be: The first loop needs to modify the contents of the element in the loop, so use the reference; But the second loop just treats the $r as a temporary variable. But why has the value of $a [1] changed?
When the iteration of the $a is complete, the $r is a reference to $a [1], changing the value of the $r, that is, changing the $a [1]. At this point, you can be surprised that the code did not modify the $r, and did not modify the $a [1] ah?
In fact, foreach is manipulating a copy of an array, so the latter iteration is equivalent to:
Copy CodeThe code is as follows:
for ($i =0; $i $r = $b [$i]; Modified the $r! equivalent to $a [1] = $b [$i];
}
In order to avoid this situation, it should be done after the first iteration
Copy CodeThe code is as follows:
Unset ($R);
Remove $R This variable (reference variable) from the current environment.
Even if this is not the case, after the first iteration, it is still very possible to execute a similar statement:
Copy CodeThe code is as follows:
$r = 123;
Loop variables are typically temporary variables, and the same variable names represent different things in different places of code, but the scope of the variables exists outside the loop. This is the disadvantage of this scope rule, plus the "variable does not declare is used" bad, plus the variable no type of disadvantage.
Therefore, using reference variables in PHP should be unset () after the reference is used. All variables should be unset () before they are used.
http://www.bkjia.com/PHPjc/325872.html www.bkjia.com true http://www.bkjia.com/PHPjc/325872.html techarticle Copy the code as follows: $a = Array (1, 2), $b = Array (one, three), and foreach ($a as//output 122 loops may have the original intention: the first loop needs to modify the contents of the element in a loop ...