php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #46716 Iterator does not work with list/each constructs
Submitted: 2008-11-29 11:16 UTC Modified: 2008-12-10 12:04 UTC
From: iain at workingsoftware dot com dot au Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: 5.2.6 OS: Freebsd 7.0
Private report: No CVE-ID: None
 [2008-11-29 11:16 UTC] iain at workingsoftware dot com dot au
Description:
------------
I can use an Iterator with foreach(), however if I attempt to iterate over it using list/each it does not behave as expected. Basically I'd just like to be able to treat an Iterator as I would an array.

Reproduce code:
---------------
sample code at:

http://www.workingsoftware.com.au/iterator_test.phpt

Expected result:
----------------
this is not so much expected, as desired result:

0: one
1: two
2: three

Actual result:
--------------
0: one
1: two
2: three
MyIteratorarr: Array

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-11-29 11:17 UTC] iain at workingsoftware dot com dot au
Sorry, my desired result should have been:

0: one
1: two
2: three
0: one
1: two
2: three
 [2008-12-10 11:48 UTC] johannes@php.net
This was recently discussed on the developers list and decided to keep the current behavior which is iterating over the object's property table
 [2008-12-10 12:04 UTC] iain at workingsoftware dot com dot au
That means there's no way to use an Iterator and advance the array pointer more than once per iteration. You can't use a for loop, and you can't use while + list/each, so you're only option is to use foreach and use the Iterator specific methods such as:

$iter->next();

etc. which precludes you from writing code that can handle arrays OR Iterators effectively (unless you actually check the type of the array/Iterator and handle it differently) such as:

if(!($my_arr instanceof Iterator))
{
    while(current($my_arr))
    {
        list($key,$value) = each($my_arr);
        //do stuff... do we need to advance the pointer again?
        //yes we do ... 
        list($key,$value) = each($my_arr);
        //do stuff... do we need to advance the pointer again?
        //not this time ... 
    }
}

else
{
    while($my_arr->valid())
    {
        ... etc ... 
    }
}

which is highly cumbersome. An Iterator should just behave like an array when it comes to Iteration, what's the point of having it not work with list/each?
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat May 18 10:01:32 2024 UTC