Patrick Galbraith

Web developer - Adelaide, Australia

PHP Foreach Reference Gotcha 1

$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;
    }
});

COMMENTS

Leave a reply

  1. Hey!
    Thanks for that quick tip but I’ve a question. I can understand why print $item returns 3, cause of the past loop used &$item.

    Why does the last loop in script prints 122?

Leave a Reply to Kaan K. Kölköy Cancel 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>