Changing array from within the foreach loop

A very basic PHP syntax thing usually ignored by developers is that you can directly update current element from within the foreach loop.

Just precede value variable with & character and it will be assigned by reference:

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}

The example above will multiply each element by 2. Otherwise, you’ll have to access source array with current element key:

$arr = array(1, 2, 3, 4);
foreach ($arr as $key=>$value) {
    $arr[$key] = $value * 2;
}

This might look as almost no difference but it could be a life saver when updating multidimensional arrays or trees in nested loops. This is because you can simply do:

...
$item = <expression>;
...

… instead of something like this:

...
$arr[$key1][$key2][$key3] = <expression>;
...

A word of caution

But be careful to do not use iterator variable after such as loop as it will change last element of the array.
For example “$value = 1234” in this code will set $arr[3] to 1234 while it might read as just assigning a value to the variable. In large functions this might happen accidentally simply because of using variable with the same name.

$arr = array(1, 2, 3, 4);
foreach ($arr as $key=>$value) {
    $arr[$key] = $value * 2;
}

...

$value = 1234;

This is because the iterator variable still holds a reference to array element it was assigned on the last loop.
To avoid this problem, simply unset the iterator variable after the loop:

$arr = array(1, 2, 3, 4);
foreach ($arr as $key=>$value) {
    $arr[$key] = $value * 2;
}
unset($value);

...

$value = 1234;

It will ensure that usage of a variable with the same name later in code will not affect the array.

Leave a Comment