How can I accomplish this in php? there are cases where I need to push more elements to the array that i’m looping through so they also get looped through:
$j = array(1,2,3);
foreach ($j as $i)
{
echo $i . "\n";
if ($i <= 3)
array_push($j, 5);
}
should print 123555 but it stops at 123.
is there a way around this in php?
foreachworks on a copy of the array, not the original array (under certain conditions). That’s why you’re not seeing the changed reflected in the loop.You will get the expected output when you loop by reference:
Output: