Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing array elements while in foreach loop in php? [duplicate]

Consider the code below:

<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
   print "key=>$key\n";
   if(!isset($arr['a']))
      $arr['a'] = 'apple';
}
?>

It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?

Please don't tell me that I could do this task with numeric based index with help of counting.

like image 654
Tarun Chabarwal Avatar asked Nov 24 '22 00:11

Tarun Chabarwal


1 Answers

Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.

$arr = array();
$arr['b'] = 'book';

reset($arr);
while ($val = current($arr))
    {
    print "key=".key($arr).PHP_EOL;
    if (!isset($arr['a']))
        $arr['a'] = 'apple';
    next($arr);
    }

Or use ArrayIterator with foreach, because ArrayIterator is not an array.

$arr = array();
$arr['b'] = 'book';

$array_iterator = new ArrayIterator($arr);


foreach($array_iterator as $key=>$val) {
   print "key=>$key\n";
   if(!isset($array_iterator['a']))
      $array_iterator['a'] = 'apple';
}
like image 169
sectus Avatar answered Apr 26 '23 23:04

sectus