Copy code The 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 intention of the two loops may be: the first loop needs to modify the content of the element in the loop, so it uses a reference; but the second loop just uses $r as a temporary variable. But , why did the value of $a[1] change?
When the iteration of $a is completed, $r is a reference to $a[1]. Changing the value of $r means changing $a [1]. At this time, you may be surprised that $r has not been modified in the code, nor has $a[1] been modified?
In fact, foreach operates on a copy of the array, so, after One iteration is equivalent to:
Copy code The code is as follows:
for($i=0; $i$r = $b[$i]; // Modified $r! Equivalent to $a[1] = $b[$i];
}
In order to avoid this situation, you should execute
Copy code after the first iteration. The code is as follows:
unset($r);
Delete the $r variable (reference variable) from the current environment.
Even if it is not the previous example, after the first iteration, It is still very possible to execute similar statements again:
Copy code The code is as follows:
$r = 123;
Loop variables are generally temporary variables. The same variable name represents different things in different places in the code, but the scope of the variable exists outside the loop. This is the disadvantage of this scope rule, plus In addition to the disadvantages of "variables can be used without declaring them", there is also the disadvantage of variables having no type.
So, when using reference variables in PHP, you should unset() them after the reference is used. All variables are in You should unset() before using it.
http://www.bkjia.com/PHPjc/325872.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325872.htmlTechArticleCopy the code as follows: $a = array(1, 2); $b = array(11, 12) ; foreach($a as // Output 12 The original intention of the two loops may be: the first loop needs to modify the content of the element in the loop...