Modify an array in a loop

Here is the code:

$arraya = array('a','b','c');
foreach($arraya as $key=>$value)
{
    if($value == 'b')
    {
        $arraya[] = 'd';
        //print_r($arraya);    //$arraya now becomes array('a','b','c','d')
    }
    echo $key.' is '.$value."\n";
}

and he will receive:

0 is a
1 is b
2 is c

And I wonder why 3 is dit is not displayed?

+3
source share
3 answers

From the PHP manual :

Note. If the array is not specified, foreach works with a copy of the specified array, and not with the array itself. foreach has some side effects to an array pointer. Do not rely on an array pointer during or after foreach without resetting it.

+9
source

$arraya = array(a,b,c);
foreach($arraya as $key=>$value)
{
    if($value == b)
    {
        $d = 'd';
        array_push($arraya, $d);
        //print_r($arraya);    //$arraya now becomes array(a,b,c,d)
    }
    print_r($arraya);
    echo $key.' is '.$value."\n";
}

you will need to print the entire array, not the individual elements one at a time. you will get the result only when printing $ arraya
if $ arraya is already "d", then it prints easily.

+1
source

, else ...

int a = 1;
if(a == 1){
   a = 0;
}
else{
   //print something;
}

foreach , foreach.

0

Source: https://habr.com/ru/post/1737369/


All Articles