Two loops are performed on an array. The value of the array element is changed by reference for the first time, and $ k, $ v, why does the value of the last element of the array change without reference? And the last element has not changed? {Code ...}
Two loops are performed on an array. The value of the array element is changed by reference for the first time, and $ k, $ v, why does the value of the last element of the array change without reference? And the last element has not changed?
&$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);
Reply content:
Two loops are performed on an array. The value of the array element is changed by reference for the first time, and $ k, $ v, why does the value of the last element of the array change without reference? And the last element has not changed?
&$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);
$ 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); // when foreach uses a reference, the reference relationship is closed immediately after processing, or the following $ v =>$ vaforeach ($ arr as $ k =>$ v) {var_dump ($ v) ;} var_dump ($ arr );
$ V = e after the first cycle; // reference link here & $ arr ['E'];
The last step of the second loop will be & $ v = $ arr ['D']; then & $ arr ['E'] = & $ v = $ arr ['D'];
This is a classic pitfall for PHP reference.
Solution: Add one after the first foreach.unset($v);You can.
The principle is omitted. you can google/baidu on your own.