On a foreach
loop, it seems PHP reads the whole array at the beginning, so if you suddenly need to append new items to the array they won't get processed by the loop:
$a = array (1,2,3,4,5,6,7,8,9,10);
foreach ($a as $b)
{
echo " $b ";
if ($b ==5) $a[] = 11;
}
only prints out: 1 2 3 4 5 6 7 8 9 10
Just create a reference copy of the array you are looping
$a = array(1,2,3,4,5,6,7,8,9,10);
$t = &$a; //Copy
foreach ( $t as $b ) {
echo " $b ";
if ($b == 5)
$t[] = 11;
}
Or Just use ArrayIterator
$a = new ArrayIterator(array(1,2,3,4,5,6,7,8,9,10));
foreach ( $a as $b ) {
echo "$b ";
if ($b == 5)
$a->append(11);
}
Output
1 2 3 4 5 6 7 8 9 10 11
See Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With