Modifying an array during a foreach loop This question is always on my mind. I usually alter the array while looping through its keys, based on my gut feelings:

foreach (array_keys($array) as $key) {
  $array[$key] = perform_changes_on($array[$key]);
}


I'm aware of other methods, though. The array item can be passed by reference on the foreach call:

foreach ($array as &amp;$item) {
  $item = perform_changes_on($item);  
}


Finally, the array can be modified directly during the loop:

foreach ($array as $key =&gt; $value) {
    $array[$key] = perform_changes_on($value);
}


What are the performance and security implications of each approach? Is there a recommended approach?

UPDATE: What I'm actually worried about is that the two last approaches modify the array while I'm looping it.
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.