PHP foreach Reference
' Val1 ', ' str2 ' = ' val2 ', ' str3 ' = ' val3 ', ' str4 ' = ' val4 ', ' $b = Array (' str1 ', ' str2 ', ' str3 ', ' STR4 ',); foreach ( $b as & $val) {$val = $a [$val];} Unset ($val), foreach ($b as $val) {echo "-----$b [3]"; Echo $val. " \ n ";}?" >
' Val1 ', ' str2 ' = ' val2 ', ' str3 ' = ' val3 ', ' str4 ' = ' val4 ', ' $b = Array (' str1 ', ' str2 ', ' str3 ', ' STR4 ',); foreach ( $b as & $val) {$val = $a [$val];} foreach ($b as $val) {echo "-----$b [3]"; Echo $val. " \ n ";}?" >
Output:
-----VAL1VAL1
-----Val2val2
-----VAL3VAL3
-----VAL3VAL3
As you can see, because the first foreach reference to the last $[2] reference is not closed, the address is already being written in the second foreach;
By printing the value of $b[2], you can see. As foreach runs, the value of $b [2] is constantly changing. This results in the value of $b [2] When foreach runs to $b[1]
is equal to $b[1], then at the last run, the $b [2] = $b [2] is the same as the $b[1].
Solution:
Use the unset () method to release the reference variable before the second foreach loop.
' Val1 ', ' str2 ' = ' val2 ', ' str3 ' = ' val3 ', ' str4 ' = ' val4 ', ' $b = Array (' str1 ', ' str2 ', ' str3 ', ' STR4 ',); foreach ( $b as & $val) {$val = $a [$val];} Unset ($val), foreach ($b as $val) {echo "-----$b [3]"; Echo $val. " \ n ";}?" >
Output Result:
-----VAL4VAL1
-----Val4val2
-----VAL4VAL3
-----VAL4VAL4
Scenario two (not very good):
' Val1 ', ' str2 ' = ' val2 ', ' str3 ' = ' val3 ', ' str4 ' = ' val4 ', ' $b = Array (' str1 ', ' str2 ', ' str3 ', ' STR4 ',); foreach ( $b as & $val) {$val = $a [$val];} Unset ($val), foreach ($b as $item) {echo "-----$b [3]"; Echo $item. " \ n ";}?" >
This is not the case if you replace the as variable in the second foreach and do not use the referenced variable.
Output:
-----VAL4VAL1
-----Val4val2
-----VAL4VAL3
-----VAL4VAL4
Summary: It is recommended to use unset () to release the reference after it is referenced.