dmmd
dmmd

Reputation: 3009

Adding new indexes to an array inside foreach

So, I have this:

$abc = array('a','b','c');
foreach ($abc as $k => &$a) {
    echo $a;
    if ($k == 1)
        $abc[] = 'd';
}

Work's as expected, iterating through the foreach 4 times and giving me:

abcd

But now, when I have this:

$myvar = $this->someModel->return_an_array_as_result(); // returns array([0] => array('a' => 'b'))

foreach ($myvar as $myvar_key => &$mv){
    $myvar[] = array('e' => 'f');
    var_dump($myvar);
    if ($myvar_key == 5) die;
}

The foreach only runs once.

Any thoughts on how foreach works when resetting the internal pointer?

Upvotes: 1

Views: 980

Answers (2)

Baba
Baba

Reputation: 95131

I see your point, you can use ArrayObject which would allow append to array while you are still loop through the array

$myvar = new ArrayObject(array('a' => 'b'));
$x = 0;
foreach ( $myvar as $myvar_key => $mv ) {
    $myvar->append(array('e' => 'f'));
    if (($x >= 4))
        break;
    $x ++;
}
var_dump($myvar);

Output

object(ArrayObject)[1]
  public 'a' => string 'b' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)
    array
      'e' => string 'f' (length=1)

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

That's because foreach is actually working on a copy of the array. If you're planning on modifying the array while you're iterating over it, use a traditional for loop.

For more information, see the PHP docs on foreach. Also, if you're looking to modify elements while iterating, you can &$reference them (more information about this also found in the foreach docs).

Upvotes: 1

Related Questions