Re: bug when using foreach with references?
| From: | mm w | Date: | Thu, 22 Oct 2009 02:19:13 +0000 |
| Subject: | Re: bug when using foreach with references? | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-45865@lists.php.net to get a copy of this message | ||
Richard, enumerator exhausted, repeat your sub-sequence again you will get it
e.g pointer and pointed
Best Regards
On Wed, Oct 21, 2009 at 7:01 PM, Richard K Miller
<richardkmiller@gmail.com> wrote:
> Hi Jill,
>
>>> <?php
>>> $items = array('apple', 'banana', 'carrot');
>>> print_r($items);
>>> foreach ($items as &$item) { }
>>
>> $item is now a reference to the last element of $items.
>>>
>>> print_r($items);
>>> foreach ($items as $item) { }
>>
>> And here, the foreach loop writes to $item for each element: thus
>> assiging that value to the last element of $items.
>
> The last element of $items is 'carrot'. Why does it print apple, banana,
> banana?
>
> It sounds like you're saying that $item should be left with the value
> 'carrot', which makes sense, but why would the original array be modified?
> (These are empty foreach loops.)
>
>>> print_r($items);
>>> ?>
>>>
>>> // Output:
>>> Array
>>> (
>>> [0] => apple
>>> [1] => banana
>>> [2] => carrot
>>> )
>>> Array
>>> (
>>> [0] => apple
>>> [1] => banana
>>> [2] => carrot
>>> )
>>> Array
>>> (
>>> [0] => apple
>>> [1] => banana
>>> [2] => banana
>>> )
>>>
>>> Two bananas in the last set?! Not what I expected.
>>
>> You can fix your bug by using 'unset($item);' after the second
>> foreach-loop.
>>
>
>
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>