Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add items to an array while looping through it?

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

like image 785
Henry Avatar asked Nov 03 '12 23:11

Henry


1 Answers

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

like image 74
Baba Avatar answered Sep 27 '22 17:09

Baba