Increasing array elements while in foreach loop in php?

This question already has an answer here:

  • How does PHP 'foreach' actually work? 7 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=>$keyn";
       if(!isset($array_iterator['a']))
          $array_iterator['a'] = 'apple';
    }
    

    I think you need to store array element continue sly

    Try

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

    In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

    http://cz2.php.net/manual/en/control-structures.foreach.php

    链接地址: http://www.djcxy.com/p/53026.html

    上一篇: 通过引用分配php

    下一篇: 在PHP的foreach循环中增加数组元素?