|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[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 PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Dec 06 14:00:01 2025 UTC |
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?