tags:

views:

82

answers:

3

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 it will get:

0 is a
1 is b
2 is c

And I wonder why 3 is d doesn't show up??

+8  A: 

From the PHP manual:

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

Andy E
+1, was about to come to this conclusion!
ILMV
+1 In other words: dont try to change the array whilst in a `foreach` loop.
Martin Wickman
janmoesen
@janmoesen: I've removed that part - it's not something I've tried before tbh.
Andy E
Felix Kling
@Felix:That's right~
SpawnCxy
+1  A: 

$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 whole array not the individual elements one by one. you will get your result only when you print $arraya
if $arraya had 'd' already in it then it would have printed easily.

Gaurav Sharma
A: 

it's the same reason that the else in the following statement will not be executed...

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

your foreach deals with an array as it is when it is evaluated by the foreach clause.

Dr.Dredel