qx3fpa
Last Updated: February 25, 2016
·
10.67K
· graup

PHP foreach pass-by-reference: Do it right, or better not at all.

php

This is an example why pass-by-reference in foreach loops is BAD.

$data = array(1,2,3,4);
foreach($data as &$entry) {
    // $entry = ...
}

echo '$data = ';
print_r($data);


/* later in your code, totally unrelated */

$test = array(10,20,30,40);
foreach($test AS $entry) {
    //
}

echo '$data = ';
print_r($data);

/**
 * Expected: array(1,2,3,4)
 * Actual: array(1,2,3,40)
 **/

This is because when the second loop executes, $entry is still a reference.
Thus, with each iteration the original reference is overwritten.

You could fix this by calling

unset($entry);

after the pass-by-reference loop. So, if you ever were to use this coding style, don't forget to unset the reference variable after the loop.

However, I think it's best to avoid this pitfall altogether and just write foreach loops that have to manipulate the original array the normal way:

foreach($data as $index => $entry) {
    // $data[$index] = ...
}