Definitely relevant for PHP 7+
1. You can't change array during iteration
Foreach WILL NOT LOOP through new values added to the array
<?php
while inside the loop.
$a = [1, 2, 3];
foreach ($a as $k => $v) {
echo $v;
if ($v === 2) {
$v[] = 4;
}
}
?>
Output: 123
But the original array was modified: [1, 2, 3, 4]
Foreach WILL LOOP through values deleted from the array while inside the loop.
<?php
$a = [1, 2, 3];
foreach ($a as $k => $v) {
echo $v;
if ($v === 2) {
unset($a[2]);
}
}
?>
Output: 123
But the original array was modified: [1, 2]
2. But If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration
Foreach WILL LOOP through new values added to the array while inside the loop.
<?php
$a = [1, 2, 3];
foreach ($v as &$v) {
echo $v;
if ($v === 2) {
$v[] = 4;
}
}
?>
Output: 1234
Foreach WILL NOT LOOP through values deleted from the array while inside the loop.
<?php
$a = [1, 2, 3];
foreach ($a as $k => &$v) {
echo $v;
if ($v === 2) {
unset($a[2]);
}
}
?>
Output: 12