Patrick Galbraith

Web developer - Adelaide, Australia

PHP Foreach Reference Gotcha 5

$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?

  2. This site truly has all the info I needed concerning this subject and didn’t know who to ask.

  3. What i do not realize is in fact how you are not really much more neatly-liked than you
    may be now. You’re so intelligent. You know
    thus significantly relating to this topic, produced me individually consider it from so many varied
    angles. Its like women and men aren’t fascinated unless it’s one thing to
    accomplish with Girl gaga! Your individual stuffs outstanding.
    All the time maintain it up!

  4. What’s up mates, its impressive post on the topic of educationand completely explained, keep
    it up all the time.

  5. If you want to grow your experience only keep visiting this web page and
    be updated with the most up-to-date news update posted here.

Leave a Reply to Lihat Sumber Info 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>