Home > Article > Backend Development > Questions about passing by reference when looping
Loop an array twice. The first time the value is passed by reference, the value of the array element is changed. The second time $k, $v are still used. Why is the last element of the array changed without using a reference? value? And the first few elements have not changed, but the last one has changed?
<code><?php $arr = array(1,2,3,4,5); foreach ($arr as $k => &$v) { switch ($v) { case '1': $v = 'a'; break; case '2': $v = 'b'; break; case '3': $v = 'c'; break; case '4': $v = 'd'; break; case '5': $v = 'e'; break; default: # code... break; } } var_dump($v); var_dump($arr); foreach ($arr as $k => $v) { var_dump($v); } var_dump($arr);</code>
Loop an array twice. The first time the value is passed by reference, the value of the array element is changed. The second time $k, $v are still used. Why is the last element of the array changed without using a reference? value? And the first few elements have not changed, but the last one has changed?
<code><?php $arr = array(1,2,3,4,5); foreach ($arr as $k => &$v) { switch ($v) { case '1': $v = 'a'; break; case '2': $v = 'b'; break; case '3': $v = 'c'; break; case '4': $v = 'd'; break; case '5': $v = 'e'; break; default: # code... break; } } var_dump($v); var_dump($arr); foreach ($arr as $k => $v) { var_dump($v); } var_dump($arr);</code>
<code>$arr = array(1,2,3,4,5); foreach ($arr as $k => &$v) { switch ($v) { case '1': $v = 'a'; break; case '2': $v = 'b'; break; case '3': $v = 'c'; break; case '4': $v = 'd'; break; case '5': $v = 'e'; break; default: # code... break; } } var_dump($v); var_dump($arr); unset($v);//foreach 使用引用时在处理完后立即断开引用关系,或则把下面的$v=>$va foreach ($arr as $k => $v) { var_dump($v); } var_dump($arr); </code>
After the first loop $v = e;//There is still a reference relationship here&$arr['e'];
The penultimate step of the second loop will be &$v = $arr['d']; then &$arr['e'] = &$v = $arr['d'];
This is a classic pitfall of PHP references.
Solution: Just add unset($v);
after the first foreach.
The principle is abbreviated, you can google/baidu yourself.