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??

1

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 In other words: dont try to change the array whilst in a foreach loop.
foreach(&$arraya as $key=>$value) is not valid syntax in PHP 5.3.
@janmoesen: I've removed that part - it's not something I've tried before tbh.
@janmoesen: It has to be foreach($arraya as $key=>&$value). The value has to be referenced. But with this you can only change the value.
1

$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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.