php - How does a reference in a for-each loop change an element of an array? -
this question has answer here:
$arr=array('a'=>'first','b'=>'second','c'=>'third'); foreach($arr &$a); foreach($arr $a); print_r($arr);
the above code changes last element of $arr ['c'=>'second']
. how that?
you creating references in first loop. @ end of loop $a
still reference last value in array:
$arr = ['a','b','c']; foreach($arr &$a); debug_zval_dump($arr,$a);
array(3) refcount(2){ [0]=> string(1) "a" refcount(1) [1]=> string(1) "b" refcount(1) [2]=> &string(1) "c" refcount(2) }
so, assigning $a change value:
//... previous code, , then: $a = 'i still reference'; debug_zval_dump($arr);
array(3) refcount(2){ [0]=> string(1) "a" refcount(1) [1]=> string(1) "b" refcount(1) [2]=> &string(22) "i still reference" refcount(2) }
... so, if second foreach, happen: last item in array take on value of first item, original value lost, , following items of array. however, when gets set (the last one), original value has been lost, , doesn't change anything, last value of array take on value of item before last:
foreach($arr $a){ debug_zval_dump($arr); }
array(3) refcount(3){ [0]=> string(1) "a" refcount(1) [1]=> string(1) "b" refcount(1) [2]=> &string(1) "a" refcount(2) } array(3) refcount(3){ [0]=> string(1) "a" refcount(1) [1]=> string(1) "b" refcount(1) [2]=> &string(1) "b" refcount(2) } array(3) refcount(3){ [0]=> string(1) "a" refcount(1) [1]=> string(1) "b" refcount(1) [2]=> &string(1) "b" refcount(2) }
in short: when using references in loop unless have very reason not to:
foreach($array &$a){ // logic } unset($a); // removes reference, can't accidentally assign , thereby mutate $array itself.
Comments
Post a Comment