PHPforeach reference & lt ;? Php $ aarray (str1 & gt; val1, str2 & gt; val2, str3 & gt; val3, str4 & gt; val4,); $ barray (str1, str2, str3, str4,); foreach ($ ba 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 last $ [2] reference of the first foreach reference is not closed, the address is constantly being written in the second foreach;
Print the value of $ B [2. With foreach running, the value of $ B [2] is constantly changing. This causes the value of $ B [2] When foreach runs to $ B [1 ].
It is equal to $ B [1]. in the last run, $ B [2] = $ B [2] is the same as $ B [1 ].
Solution:
Use the unset () method to release the referenced 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
Solution 2 (not 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";}?>
Replace the as variable in the second foreach without using the referenced variable.
Output:
----- Val4val1
----- Val4val2
----- Val4val3
----- Val4val4
Conclusion: We recommend that you use unset () to release it after Reference.