Last Updated: February 25, 2016
· graup

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

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 = ';

/* later in your code, totally unrelated */

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

echo '$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


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] = ...