Looping through values using reference

by rp

There are times where you need to loop through a large array and manipulate the items in the array. This is what you usually do.

  • List through items
  • Create a temp array which contains the modified values
  • Exit the loop and re-assign the new array back to the actual array.

This works fine, other than there are some problems with that.

  • You need to create a temp array
  • Make sure you assign it back to the original array (People make mistakes of not doing that assignment)

So here’s a simpler more easy way to handle this.

$items= array('key1' => 1, 'key2' => 12, 'key3' => 3);
foreach($items as $item => &$value) {
        $value += 20;
        print "$item: $value";
}
var_dump($items);

Note that the $value is assigned a reference, so it doesnt work on a copy of the value but the actual value and hence it retains its value even after exiting the loop. Saw this snippet in symfony so thought it was worth mentioning.