Because after you are out of the first foreach loop, $value still remains a pointer to $arr[3] (where you were expecting 8 to be). So when you run the second foreach, becasue it is done normally, $value is still a variable that received the value of the current element. (receiving 2, 4, 6...) BUT $value is really $arr[3], so each time you are putting a new value in $arry[3], and so when you got to where you expected $value to be 8, it was actually 6 from being given that value the last time through.
Basically, your second foreach loop is equivalent to :
Code: Select all
foreach ($arr as $arr[3]) {
echo $arr[3]."<br/>";
}
echo $arr[3];
This is why in the example they point out to do a
unset ($value); after the foreach loop to break the reference back to $ary[3]
To see this demonstrated further, try the following code.
If you follow the output, you will notice that on the var_dump, the element that has $value is pointing to is indicated with a & in front of it. The first foreach, it goes through each of them. Between the foreach loops, you will see it still references $arr[3]. Notice then during the second loop, whatever element it is on, $arr[3] is now set to that elements value.
Code: Select all
<?php
$arr = array(1, 2, 3, 4);
echo "<pre><tt>BEGINNING: ";var_dump($arr);echo "</tt></pre>\n";
foreach ($arr as $key=>&$value) {
echo "<pre><tt>1st Loop [Key:$key]: ";var_dump($arr);echo "</tt></pre>\n";
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
echo $value."<br/>";
echo "<pre><tt>MIDDLE: ";var_dump($arr);echo "</tt></pre>\n";
foreach ($arr as $key=>$value) {
echo "<pre><tt>2nd Loop [Key:$key]: ";var_dump($arr);echo "</tt></pre>\n";
echo $value."<br/>";
}
echo "<pre><tt>ENDING: ";var_dump($arr);echo "</tt></pre>\n";
echo $value;
?>