A strange phenomenon occurred when using foreach, where the last value of an array variable was somehow modified, and the PHP manual foreach description found
Warning
The $value reference of the last element of the array remains after the Foreach loop. It is recommended to use unset () to destroy it.
There is such a warning. Use the Unset method or use a different variable name.
For example
$a =[1,2];foreach ($a as $key = = $value) { $a [$key]= $value +1;} echo $value;//Output 2
If a pointer is used in $ A, the value of the variable with the same name will be affected, with the following result:
$a =[1,2]; $b =[3,4];foreach ($a as $key =>& $value) { $a [$key]= $value +1;} Print_r ($a); foreach ($b as $value) { $value + +;} Print_r ($a);p rint_r ($b); the output is as follows array ( [0] = 2 [1] = 3) array ( [0] = 2 [1] + 5) Array ( [ 0] = 3 [1] = 4)
If you use pointers or use unset, they are unaffected
$a =[1,2]; $b =[3,4];foreach ($a as $key =>& $value) { $a [$key]= $value +1;} Print_r ($a); foreach ($b as & $value) { $value + +;} Print_r ($a);p rint_r ($b); Enter the following array ( [0] = 2 [1] = 3) 3Array ( [0] = 2 [1] = 3) Array ( C14/>[0] + 4 [1] = 5)
Using unset
$a =[1,2]; $b =[3,4];foreach ($a as $key =>& $value) { $a [$key]= $value +1;} Print_r ($a), unset ($key, $value), foreach ($b as $key = $value) { $b [$key]= $value +1;} Print_r ($a);p rint_r ($b); the output is as follows array ( [0] = 2 [1] = 3) array ( [0] = 2 [1] + 3) array ( [ 0] = 4 [1] = 5)
Variables in the PHP foreach Loop