The use of foreach and references in PHP results in a problem introduction to the program BUG

  • 2020-05-19 04:23:37
  • OfStack

 
$a = array(1, 2); 
$b = array(11, 12); 
foreach($a as &$r){ 
} 
foreach($b as $r){ 
} 
echo $a[1]; //  The output  12 

The first loop needs to modify the content of the element in the loop, so use a reference. But the second loop only treats $r as a temporary variable, so why has the value of $a[1] changed?

When the iteration of $a is completed, $r is a reference to $a[1]. Changing the value of $r is changing $a[1].

In fact, foreach operates on a copy of the array, so the next iteration is equivalent to:
 
for($i=0; $i<count($b); $i++){ 
$r = $b[$i]; //  To modify the  $r!  The equivalent of  $a[1] = $b[$i]; 
} 

To avoid this, execute after the first iteration
 
unset($r); 

Remove the $r variable (the reference variable) from the current environment.

Even if it is not the previous example, it is still possible to execute similar statements after the first iteration:
 
$r = 123; 

Looping variable 1 is usually a temporary variable, and the same variable name means different things in different parts of the code, but the scope of the variable exists outside of the loop. This is the disadvantage of this scoping rule, plus the disadvantage of variables not being declared and used, plus the disadvantage of variables not being typed.

Therefore, when using reference variables in PHP, they should be unset() after the reference is used. All variables should be unset() before they are used.

Related articles: