Copy Code code as follows:
$a = Array (1, 2);
$b = Array (11, 12);
foreach ($a as & $r) {
}
foreach ($b as $r) {
}
echo $a [1]; Output 12
The two cycle is meant to 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 $r as a temporary variable. But why has the value of the $a [1] changed?
When the $a iteration is complete, the $r is a reference to the $a [1], changing the value of the $r to change 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 the copy of an array, so the latter iteration is equivalent to:
Copy Code code as follows:
for ($i =0; $i <count ($b); $i + +) {
$r = $b [$i]; Modified the $r! equivalent to $a [1] = $b [$i];
}
To avoid this, after the first iteration, you should execute the
Copy Code code as follows:
Deletes $r this variable (reference variable) from the current environment.
Even if it is not the previous example, after the first iteration, it is still quite possible to execute a similar statement:
Copy Code code as follows:
A loop variable is generally a temporary variable, and the same variable name represents something different in the code, but the scope of the variable is outside the loop. This is the disadvantage of this scoping rule, plus the bad of "variable is not declared to be used", plus the variable has no type of disadvantage.
Therefore, the use of reference variables in PHP, should be used after the reference should be unset (). All variables should be unset () before they are used.