callmebob
callmebob

Reputation: 6323

foreach doesn't print altered array properly

I am trying to print an array using foreach and while printing, if a certain $key comes up, I want to make changes to the array. Problem is, even though the array gets changed, the changes do not get printed.

In the example below, you will find:

Note that the new $key is to jump in AFTER current $key, so I would expect it to come up. Any idea why this happens ?

EDIT:

Played a bit more with foreach and I think it must be caching the keys or something...

    <?php
    $test_array = array(0,1,2,3,4,5,6,7,8,9);

    foreach ($test_array as $key => $value) {
        if ($key === 5){$test_array[7] = $test_array[7]+1;}
        echo $key . ": " . $value . "<br />";
    }

    print_r($test_array);
    ?>

The above will display UNCHANGED echo, but CHANGED print_r.

Upvotes: 2

Views: 247

Answers (3)

shudder
shudder

Reputation: 2101

I'd keep it simple. Something tells me however that you're fixing effects of a problem here and not its source.

$array = array(
    "no_color"  =>  "blank",
    "color1"    =>  "red",
    "color2"    =>  "green",
    "color3"    =>  "blue",
);

$temp_array = array();

foreach ($array as $key => $value) {
    $temp_array[$key] = $value;
    echo $key . ": " . $value . "<br />";
    if ($key == 'color1') {
        $key_add = 'color1.5';
        $value_add = 'yellow';
        $temp_array[$key_add] = $value_add;
        echo $key_add . ": " . $value_add . "<br />";
    }
}

$array = $temp_array;

Upvotes: 0

Scott Saunders
Scott Saunders

Reputation: 30394

From the manual: "As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior." http://php.net/manual/en/control-structures.foreach.php

You shouldn't modify an array you're looping over.

Upvotes: 3

MontrealDevOne
MontrealDevOne

Reputation: 1044

So during iteration you are trying to change the value of the item being iterated

foreach($array ...)
{
    change $array
}

Use a copy of $array inside the iteration

 $array2 = $array
 foreach($array ...)
{
    change $array2
}

Upvotes: 3

Related Questions