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

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to