0

Why does this:

<?php

$a = array( 1, 2, 3 );

echo "First iteration:\n";

foreach ( $a as $b => &$c ) { 
    echo $c . "\n";
}

echo "\nSecond iteration:\n";

foreach ( $a as $b => $c ) { 
    echo $c . "\n";
}

Produce this:

First iteration:
1
2
3

Second iteration:
1
2
2

I'm expecting the second iteration to produce the same result as the first, shouldn't I?

Observe that the difference is "element by reference" in the first foreach.

Rikard
  • 83
  • 1
  • 9
  • Can you do var_dump($a) after each iteration to see if the original array itself has somehow changed ? – Maximus2012 Mar 26 '15 at 15:23
  • [strange behavior of foreach](http://stackoverflow.com/questions/4969243/strange-behavior-of-foreach/4969286#4969286) – Mark Baker Mar 26 '15 at 15:44

0 Answers0