Sometimes we want to change the value of the array item in the loop, the variable entry can be a & match when foreach,
Indicates that the original value in the array is used in the loop, instead of a copied value, such as
foreach ($array as & $item) {}
In this way, when we modify the value of the $item in the loop, we actually modify the corresponding value in the $array.
If you do not add the & symbol, changing the value of $item in the loop does not affect the $array.
Example:
$array = [ ' name ' = ' Jobs ', ' age ' = 50,];foreach ($array as $key = = $value) { $value = 22;} Print_r ($array); foreach ($array as $key = & $value) { $value = 22;} Print_r ($array);
Array ( = Jobs )Array( = = >)
Traps: Two cycles using the same temporary variable, if the first loop uses a reference,
The temporary variable is also referenced in the second loop, even if there is no & symbol.
This reference points to the last element in the array (looping to the end of the last element).
Example:
$array = [ ' name ' + ' php ', ' age ' + 123,];foreach ($array as $key = & $value) { echo "key= $ke Y, value= $value ". Php_eol;} foreach ($array as $key = $value) { echo "key= $key, value= $value". Php_eol;}
Key=name, Value=phpkey=age, Value=123key=name, Value=phpkey=age, value=php
The value of the last line above is "PHP", not the 123 we expect, because in the second foreach Loop,
Each time the loop is changed, the value of key ' age ' in $array is modified,
In the first loop, the age in the array is already PHP (the first value), and in subsequent loops the last value in the array is changed sequentially.
To the last loop, the value obtained is prev ($array), which is PHP.
How to avoid this problem?
1, before the second cycle, unset ($value)
2. The second foreach uses variables of different names, such as $item
Another: see if a variable is a reference you can use the Xdebug_debug_zval function (you need to have a xdebug extension).
The results of Xdebug_debug_zval are as follows:
Value: (refcount=2, Is_ref=1) =123
foreach in PHP uses a referenced trap