Patrick Galbraith

Web developer - Adelaide, Australia

PHP Foreach Reference Gotcha

$items = array(1, 2, 3);

foreach($items as &$item) {
    echo $item;
}

// prints: 123

echo $item;

// prints: 3

foreach($items as $item) {
    echo $item;
}

// prints: 122

What?
This happens because after the first loop $item maintains the reference to 3.

Of course PHP does not have block scoping so we then assign that reference to the current loop item in the second loop overwriting the initial value.

The fix. Always unset the item after the closing brace.

foreach($items as &$item) {
    echo $item;
} unset($item);

Or put it in a self-invoking function.

call_user_func(function() use (&$items) {
    foreach($items as &$item) {
        echo $item;
    }
});

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>