Ashley Sheridan​.co.uk

Pass Values by Reference in foreach Loops

Posted on

Quite often, the question comes up about how to modify elements of an associative array inside a foreach loop, because the foreach loop passes by value, essentially creating a duplicate array in memory which your code works on. While this is usually not an issue, it can be if you want to actually modify the array.

There are two ways in which you can do this, use the key of each element to modify the original array, or pass by reference:

$cat = Array('name' => 'Greebo', 'legs' => 4, 'heads' => 1, 'colour' => 'grey'); foreach($cat as $key => $value) { if($key == 'colour') { $cat[$key] = 'black'; } } foreach($cat as $key => &$value) { if($key == 'colour') { $value = 'black'; } }

The trick with the passing by reference is just the & character, which is used in PHP (and many other languages) to pass the value by reference rather than value. Without getting too technical, this just means that a copy isn't created in memory, but that the actual object itself is used.

You'll also note, that it results in a lot less code, is still easy to understand, and if you are processing large arrays in your scripts, then it reduces the negative effect on memory that the normal foreach would.