Looping through values using reference

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.

About rp

Architect for large, highly scalable LAMP applications and Technical Manager with special focus on metrics based continuous improvement of teams and products. Rajat has close to a decade of experience of a very wide range of skills related to infrastructure, middleware, app servers all the way to front-end technologies and software development methodologies including agile, iterative waterfall, waterfall as well as ah-hoc startup using the right approach in the right context to reduce time to market.