Be careful with iterating arrays by reference

Published on May 11, 2009

Be careful with iterating arrays by reference

    I just stumbled upon a very unpleasant PHP feature when iterating through arrays with reference to elements (foreach construction with &).

    See for yourself:
    $test = array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5);
    print_r($test);
    foreach ($test as $key => $value) {
    	echo "{$key} => {$value}\n";
    }


    We get what we expected:
    Array
    (
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] => 5
    )
    1 => 1
    2 => 2
    3 => 3
    4 => 4
    5 => 5


    But it’s worth adding an iteration by reference:
    $test = array('1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5);
    foreach ($test AS &$value) {
    	// какие-то действия. Но для теста и пустого цикла достаточно
    }
    print_r($test);
    foreach ($test as $key => $value) {
    	echo "{$key} => {$value}\n";
    }


    ... how to get an unexpected result:
    Array
    (
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] => 5
    )
    1 => 1
    2 => 2
    3 => 3
    4 => 4
    5 => <b>4</b>


    I do not fully understand what the jamb is, it is somehow connected with the fact that in $ value there is a link to the last element after exiting the first loop. There are two ways to avoid this behavior: Either you need to iterate the second loop by reference too, or use a different name instead of $ value.