1

Possible Duplicate:
Strange behaviour after loop by reference - Is this a PHP bug?

Consider this code:

$start = array("a", "b", "c");  

foreach ($start as &$item) {}
foreach ($start as $item) {}

print_r($start);

When I foreach over the array and use the elements as reference, and then foreach again, but this time using normal variables, but keeping the same variable name as the refrence's, the last element of the input array is overwritten with the contents of the previous one.

The above code outputs:

Array
(
    [0] => a
    [1] => b
    [2] => b
)

Could anyone explain me why this happens? I imagine it's a memory addressing issue, but can't find any logic in this phenomenon. What exactly goes on behind the scenes here?

Community
  • 1
  • 1
mingos
  • 23,778
  • 12
  • 70
  • 107
  • My brain is full of fudge. This should be a bug report as I don't see that this wanted behaviour at all. I am reproducing this in php5.3.6 and php5.1.6 if it's of any help. – nyson May 09 '12 at 11:10
  • 2
    @nyson: This is known behaviour, that's why the [documentation](http://www.php.net/manual/en/control-structures.foreach.php) contains: *"**Warning:** Reference of a **`$value`** and the last array element remain even after the **foreach** loop. It is recommended to destroy it by `unset()`."* – Felix Kling May 09 '12 at 11:11
  • @FelixKling: Thank you, I calms be down a bit that it's known. I'd still like scoped loops in PHP though. – nyson May 09 '12 at 11:29
  • @FelixKling: thank you very much for the information and for pointing to the correct answer. Apologies for creating a duplicate. – mingos May 09 '12 at 11:30

0 Answers0