Skip to content

Instantly share code, notes, and snippets.

@jurosh
Last active February 4, 2016 09:46
Show Gist options
  • Save jurosh/dd7250f5f4de9d562f6e to your computer and use it in GitHub Desktop.
Save jurosh/dd7250f5f4de9d562f6e to your computer and use it in GitHub Desktop.
PHP iterate by reference - weaknesses
<?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