0

I have a simple multidimensional array. I modify it - ie. I add data to it - in a foreach loop, accessing its elements by reference:

 $array = array(
    array('id' => 12, 'name' => 'John1', 'surname' => 'Smith1'),
    array('id' => 13, 'name' => 'John2', 'surname' => 'Smith2'),
    array('id' => 14, 'name' => 'John3', 'surname' => 'Smith3'),
    array('id' => 15, 'name' => 'John4', 'surname' => 'Smith4'),
 );

 foreach($array as &$a) {
    $a['middlename'] = 'Robert';
 }

Now what's below shows that $array is perfectly in order:

print('<pre>'.print_r($array,true).'</pre>'); results in:

    Array
    (
        [0] => Array
            (
                [id] => 12
                [name] => John1
                [surname] => Smith1
                [middlename] => Robert
            )

        [1] => Array
            (
                [id] => 13
                [name] => John2
                [surname] => Smith2
                [middlename] => Robert
            )

        [2] => Array
            (
                [id] => 14
                [name] => John3
                [surname] => Smith3
                [middlename] => Robert
            )

        [3] => Array
            (
                [id] => 15
                [name] => John4
                [surname] => Smith4
                [middlename] => Robert
            )

    )

But while I loop though it, internal pointer stops right before last element:

 foreach($array as $a) {
     print('<pre>'.print_r($a['id'],true).'</pre>');
 }

outputs:

 12
 13
 14
 14

Any hints what's going on?

UPDATE: The answer I picked is correct and moreover I found this: PHP Pass by reference in foreach Thx, SO.

Community
  • 1
  • 1
  • ALRIGHT, got it: http://stackoverflow.com/questions/3307409/php-pass-by-reference-in-foreach – user2785626 Sep 16 '13 at 23:26
  • Using the same variable in successive `foreach` loops leads to some odd behaviour - I'll find the link if I can. Try `unset $a` between the two loops. –  Sep 16 '13 at 23:28
  • This is clearly warned about in the documentation for foreach (http://www.php.net/manual/en/control-structures.foreach.php) in the section about loop variable by reference. "Warning Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()." – newacct Sep 18 '13 at 02:27

2 Answers2

1

I've had a similar issue, when modifying an array with a foreach and then accessing the array afterwards. My guess is that you are not destroying the reference after you loop through, and are overwriting the value accidentally. Try unset($a); after your foreach.

Tom Lagier
  • 360
  • 1
  • 12
0

I would suggest not to use variable names like $array, just in case...