$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 $item
returns3
, cause of the past loop used&$item
.Why does the last loop in script prints
122
?