Re: bug when using foreach with references?

From: Date: Thu, 22 Oct 2009 16:49:39 +0000
Subject: Re: bug when using foreach with references?
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-45872@lists.php.net to get a copy of this message
On 09-10-21 07:47 PM, Marco Tabini wrote:
On 2009-10-21, at 10:40 PM, Richard K Miller wrote:
I don't follow. Is this really the intended behavior? It seems quite unintuitive that the original array would be modified by *empty* loops.
It is intended behaviour. Consider your code; at the end of this loop:
$items = array('apple', 'banana', 'carrot'); print_r($items); foreach ($items as &$item) { }
$item will contain a reference to the last item of $items. Therefore, when you start the next loop:
foreach ($items as $item) { }
$item will receive each of the values stored in $items, in sequence. But $item is a reference to the last item in $items, so whatever you write into it will also be written into the last item of the array. Thus, the loop will cause these values to be written there: - On the first iteration, "apple" - On the second iteration, "banana" - On the third iteration, "banana" (because you are taking the third item in the array, which you just overwrote)
When would this behavior be desired?
Probably never, but that does not make it counterintuitive—the interpreter is behaving correctly based on the data it is handling and the instructions you are giving to it. The correct solution, as someone has already recommended, is to unset the iterator if you want to reuse it.
Marco, thanks for the nice, clear explanation of this issue. Probably the best place for the OP was PHP General or something, but it's great when someone takes the time to respond thoughtfully. cheers, Jeff

« previous php.internals (#45872) next »