menu

Questions & Answers

is nested foreach in php with \Iterator Interface still a problem?

I am currently working on fixing a bug (in my software) that i tracked down to what i think is a singleton in my collection. Every time i loop over the collection i reset the position to 0 , so as far as i understand every loop that is running the same object will be affected.

class Collection implements \Iterator {..}

$coll = new Collection();
foreach ($coll as $a) { // loop A
    foreach($coll as $b) { // loop B
        // triggers rewind and affects loopA
    }
}

i am pretty sure i am missing something big or maybe i am trying something that should be solved differently? should i create a copy for every loop do? but i do want the object to share the same data but just not the position? should i create a unique key for every rewind and store different position for each in an array of positions? (sounds doable but .. wrong? there must be a better way.. right?)

i found this 12y thread that describes the same problem but i hope something has changed in that time? Do people just dont do it and use arrays instead? have other languages the same problem?

nested foreach with iterator interface

Comments:
2023-01-17 23:01:04
@Barmar yes, thx. fixed it
2023-01-17 23:01:04
I don't think this is considered a bug that should be fixed. Why can't you create two iterators that reference the same data?
2023-01-17 23:01:04
@Barmar well the bug is in my software , I was not trying to say that php is bugged. You gave me already a good hint / solution. Still hard to wrap my head around it that there is not a common / easy way to do it
2023-01-17 23:01:04
As the other question explains, the reason this works for arrays is because they're treated as values, not objects. So each loop gets it own copy, and has its own state. But when you use your own class, the state is in the instance, not the loop. A single iterator can't have multiple positions.
Answers(0) :