$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;
}
});
Hey!
Thanks for that quick tip but I’ve a question. I can understand why
print $itemreturns3, cause of the past loop used&$item.Why does the last loop in script prints
122?This site truly has all the info I needed concerning this subject and didn’t know who to ask.
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!
What’s up mates, its impressive post on the topic of educationand completely explained, keep
it up all the time.
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.