Oct 20 at 12:56am, Richard K Miller said:

> On Oct 20, 2009, at 12:10 AM, Richard K Miller wrote:
>
>> Is this a bug in PHP?
>
> These reports describe the issue (though more verbosely):
>
> http://bugs.php.net/bug.php?id=29992
> http://bugs.php.net/bug.php?id=31118
> http://bugs.php.net/bug.php?id=31125
> http://bugs.php.net/bug.php?id=36240
>
> Seems odd for Derick and Andi to disregard this as "expected
> behavior". The fix is to unset() the iterator value before the second
> foreach loop. (Why should that be necessary?)

After the first foreach loop, wher $item was set by reference, $item is 
still set (by reference) after you exit the loop. (There is no special 
scope for inside a foreach loop, so &$item is set in the global scope.)
When the next foreach loop sets $item, it was still set by reference, so 
it is probably overwriting that location as it sets $item the second time.

I think the docs on foreach (or on references or iterators) make mention 
of weird things that can happen when you do a foreach by reference or when 
you change the array you're iterating through.

I know several times where instead of doing a foreach by reference I've 
done something like this, making the update explicit:

foreach ($items as $k => $item) {
   // make some changes to $item here
   // ...

   // Save the changes:
   $items[$k] = $item;
}

Mac


> <?php
> $items = array('apple', 'banana', 'carrot');
> print_r($items);
> foreach ($items as &$item) { }
> print_r($items);
> unset ($item); // required
> foreach ($items as $item) { }
> print_r($items);
>
>
>
> _______________________________________________
>
> UPHPU mailing list
> [email protected]
> http://uphpu.org/mailman/listinfo/uphpu
> IRC: #uphpu on irc.freenode.net
>

--
Mac Newbold                     Code Greene, LLC
CTO/Chief Technical Officer     44 Exchange Place
Office: 801-582-0148            Salt Lake City, UT  84111
Cell:   801-694-6334            www.codegreene.com

_______________________________________________

UPHPU mailing list
[email protected]
http://uphpu.org/mailman/listinfo/uphpu
IRC: #uphpu on irc.freenode.net

Reply via email to