Php loop and reference code
$ 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 a $ valueand the last array element remain even after the foreachloop. 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.