php - why the last element of array changed after 2 foreach loop? -
this question has answer here:
- strange behavior of foreach 2 answers
what's magic? last element of $data changed, after 2 each loop.
<?php $data = array("1" => "a", "2" => "b"); print_r($data); foreach($data $k=>&$v) {} foreach($data $k=>$v) {} print_r($data);
output:[2] => after second foreach
array ( [1] => [2] => b ) array ( [1] => [2] => )
it code change this,the array won't change:
<?php foreach($data $k=>&$v) {} foreach($data $k=>&$v) {}
from foreach manual:
warning reference of $value , last array element remain after foreach loop. recommended destroy unset().
so @ end of first foreach
, $v
reference last element in array. next foreach
's first iteration changes value of $v
(to value of first array element) reference last element in array, changed.
$data = array("1" => "a", "2" => "b"); print_r($data); foreach($data $k=>&$v) {} unset($v); // *** unset here *** foreach($data $k=>$v) {} print_r($data);
result:
array ( [1] => [2] => b ) array ( [1] => [2] => b )
Comments
Post a Comment