Last active
February 4, 2016 09:46
-
-
Save jurosh/dd7250f5f4de9d562f6e to your computer and use it in GitHub Desktop.
PHP iterate by reference - weaknesses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
http://stackoverflow.com/questions/3307409/php-pass-by-reference-in-foreach | |
$a = array ('zero','one','two', 'three'); | |
foreach ($a as &$v) { | |
// nothing | |
echo $v . PHP_EOL; | |
} | |
// unset($v); | |
echo '<br>'; | |
foreach ($a as $v) { | |
echo $v . PHP_EOL . ' [' . $a[3] . ']<br>'; | |
} | |
// Because on the second loop, $v is still a reference to the last array item, so it's overwritten each time. | |
// echo $v.'-'.$a[3].PHP_EOL; | |
// As you can see, the last array item takes the current loop value: 'zero', 'one', 'two', and then it's just 'two'... : ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment