PHP Pass by reference in foreach -
this question has answer here:
- strange behavior of foreach 2 answers
i have code:
$a = array ('zero','one','two', 'three'); foreach ($a &$v) { } foreach ($a $v) { echo $v.php_eol; }
can explain why output is: 0 1 2 two .
from zend certification study guide.
because on second loop, $v
still reference last array item, it's overwritten each time.
you can see that:
$a = array ('zero','one','two', 'three'); foreach ($a &$v) { } foreach ($a $v) { echo $v.'-'.$a[3].php_eol; }
as can see, last array item takes current loop value: 'zero', 'one', 'two', , it's 'two'... : )
Comments
Post a Comment