PHP loops with reference to a pit, PHP loop reference
On the Code
$arr Array ( ' a ' = ' A11 ', ' b ' = ' B22 ', ' c ' = ' C33 ',); foreach ($arras$k=>&$v) { // do Somethind}foreach ($arras$k= =$v ) { var_dump($v);}
What will the var_dump output like in this code? You can try, the answer.
string (3) "A11"string(3) "B22"string(3) "B22"
In the result, the third line becomes the value of key= ' B '. The problem is the reference to the first loop.
Today, stepping on a hole like this, it took a long time to check the problem. In short, the Foreach Loop uses a reference that is retained after the loop has ended. Php.net emphatically wrote:
Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset ().
For this example, the $v reference still exists after the first loop has ended. Since the variables of the two loops are named consistent, the second loop starts, and $v are assigned each time. Until the end, $v was set to
The value of the previous element.
The principle is simple, the document is written plainly. But if the work encountered the relevant bug is very pit, positioning takes a long time. You have to pay attention when you need to write the code:
1. Reduce the use of references
2. If you need to use references in Foreah, you should use functions to encapsulate them
http://www.bkjia.com/PHPjc/1098446.html www.bkjia.com true http://www.bkjia.com/PHPjc/1098446.html techarticle PHP loops with reference to a pit, PHP loop reference on Code $arr = Array (' A ' = ' A11 ', ' b ' = ' b22 ', ' c ' = ' c33 ',); foreach ($arr as $k = $v) {//Do som Ethind} foreach ($arr as ...