Php loops and references
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.