Re: bug when using foreach with references?
| From: | Marco Tabini | Date: | Thu, 22 Oct 2009 02:47:41 +0000 |
| Subject: | Re: bug when using foreach with references? | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-45867@lists.php.net to get a copy of this message | ||
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:
$item will contain a reference to the last item of $items. Therefore, when you start the next loop:$items = array('apple', 'banana', 'carrot'); print_r($items); 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)foreach ($items as $item) { }
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. Cheers, Marco.