Php loops and references. Php loops and references. php loops reference code $ arrarray (aa11, bb22, cc33,); foreach ($ arras $ k $ v) {Dosomethind} foreach ($ arras php loop and reference a pitfall, php loop reference
Code on
$arr = array( 'a'=> 'a11', 'b'=> 'b22', 'c'=> 'c33',); foreach ($arr as $k=>&$v){ // Do somethind}foreach ($arr as $k=>$v){ var_dump($v);}
What will var_dump output with such code? You can try it.
string(3) "a11"string(3) "b22"string(3) "b22"
In the result, the third row is the value of key = 'B'. the problem lies in the reference of the first loop.
Today, I stepped on such a pitfall and it took a long time to check the problem. In short, the reference used by the foreach loop is retained after the loop ends. php.net is rewritten:
Warning
Reference of$ ValueAnd the last array element remain even afterForeachLoop. It is recommended to destroy it by unset ().
For the above example, after the first loop ends, the $ v reference still exists. because the variables in the two loops are named the same, $ v is assigned each time starting from the second loop. until the end, $ v is set
The value of the previous element.
The principle is very simple, and the document is clearly written. However, if you encounter bugs in your work, it will take a long time to locate the issue. you should pay attention to the following when you need to write code:
1. reduce the use of references
2. if you need to use a reference in foreah, use the function to encapsulate it.
Code $ arr = array ('a' = 'a11', 'B' = 'b22', 'C' = 'c33',) on the outputs ',); foreach ($ arr as $ k = $ v) {// Do somethind} foreach ($ arr...