Search code examples
phparraysforeachphp-5.3

foreach change last element


Possible Duplicate:
Strange behavior Of foreach

Why PHP sometimes change last element of array?

I have a array:

Array
(
    [0] => a_
    [1] => b_
    [2] => c_
    [3] => d_
)

When I try print out all emenets. And output is:

a_
b_
c_
c_

Full code is:

<?
$a = array('a', 'b', 'c', 'd');

foreach ($a as &$value)
    $value = "{$value}_";

print_r($a);

foreach ($a as $value) {
    echo "$value\n";
}

Why?


Solution

  • Either using a different variable name in your second loop or unsetting $value after your first one will solve this problem.

    $a = array('a', 'b', 'c', 'd');
    
    foreach ($a as &$value) {
        $value = "{$value}_";
    }
    
    unset($value);
    
    print_r($a);
    
    foreach ($a as $value) {
        echo "$value\n";
    }