Modifying an array during a foreach loop
If you are worried about modifying the array while looping, don't because foreach copies the array. Try 

$array = array('foo');
foreach ($array as $k =&gt; &amp;$item) {
  $array[] = 'bar';
}
var_dump($array);


And see it terminates just fine. foreach ($array as $k =&gt; &amp;$v) is a shorthand for foreach (array_keys($array) as $k) $v = &amp;$array[$k] so while there still is a copy of the array (that's why I used &amp;$item in my example so you can see, if you modify the array then it'll be modified in the reference!

$array = array('foo', 'bar');
foreach ($array as $k =&gt; $item) {
  echo "$item\n";
  if (!$k) {
    $array[1] = 'baz';
  }
}
$array = array('foo', 'bar');
foreach ($array as $k =&gt; &amp;$item) {
  echo "$item\n";
  if (!$k) {
    $array[1] = 'baz';
  }
}


the first dump foo and bar, the second foo and baz.