DEV Community

Discussion on: Iterator in PHP (A practical guide)

godsgood33 profile image
Ryan P • Edited

How would you implement a solution where the collection indexes didn't start at 0? In the project I'm working on, there are several places where traversal of a large array takes too long, so I specify the index with a known number. Then I can do a isset($arr[$obj->id]) to find, retrieve, delete, or overwrite the object at that position. I tried to implement this adapting your code but it creates a problem with the $position variable in the iterator. In PHP 7.3 they added a array_key_first() method to more easily get the first key, but I'm operating in 7.2. I've tried a foreach hack, but it creates an internal loop in the iterator.

damnjan profile image
Damnjan Jovanovic Author

Hei Ryan,
I found your question interesting, so I decided to answer in a longer form with a whole blog post. Please let me know did I answer your question and let me know if I could make it better.