dynamically changing array in foreach

后端 未结 3 1633
你的背包
你的背包 2021-01-27 04:19

is it possible somehow change array which is processed by foreach? I tried this script

$iterator = 10;
$cat = array(1 => \'a\',2 => \'b\',3 => \'c\');

         


        
相关标签:
3条回答
  • 2021-01-27 04:28

    Actually, you should not. Because foreach will work with copy of array. That means - it will firstly copy your array and then loop through it. And no matter if you'll change original array - since you're working with it's copy inside foreach, any modification will affect only original array and not looped copy.

    But - yes, after foreach you will see your changes in original array. Besides, there is little sense in doing such thing. It's hard to read and may case unpredictable results.

    One important thing that wasn't mentioned. The following wont work:

    $iterator = 10;
    $cat = array(1 => 'a');//only one element; same for empty array
    
    foreach ($cat as $k => &$c)
    {
        if ($iterator < 15)
        {
            $cat[$iterator] = $iterator;
            $iterator++;
        }
        echo $c;
    }
    

    -because of how PHP deals with array pointer in foreach.

    0 讨论(0)
  • 2021-01-27 04:33
    <?php
    $iterator = 10;
    $cat = array(1 => 'a',2 => 'b',3 => 'c');
    
    foreach ($cat as $k => &$c)//observe the '&'
    {
        if ($iterator < 15)
        {
            $cat[$iterator] = $iterator;
            $iterator++;
        }
        echo $c;
    } 
    ?>
    
    0 讨论(0)
  • 2021-01-27 04:37

    The internet needs more cats! pass the array by reference instead and you'll get the desired result. note the &$cat in the loop.

    $iterator = 10;
    $cat = array(1 => 'a',2 => 'b',3 => 'c');
    
    foreach($cat as $k => &$c)
    {
        if ($iterator < 15)
        {
            $cat[$iterator] = $iterator;
            $iterator++;
        }
        echo $c;  
    }
    
    0 讨论(0)
提交回复
热议问题