Master PHP Iterators

Demystifying one of the most powerful tool you’ll encounter

Alexandre Daubois
Geek Culture

--

A few words about iterators

You may have heard of them. You may even use them without knowing it. Iterators are super powerful tools that could have simplify your life and solve your biggest problems in a few lines of codes.

But first, let’s dive a bit in design patterns (I promise it will be short) to fully understand what we’re talking about here.

Collections are one of the most useful data representation for developers, and maybe the most used one as well. Most of the time, we’re dealing collection that are simple lists: each element follows each other without complex order. But of course, that’s not the only type of collection that exists. We can cite for example stacks, graphs, trees, binary trees, or even more complex structures. And here are two problems:

  • At this point, we’re not able to loop through these collections with a classic for loop ;
  • If your collection is pretty big and contains like millions, even hundreds of millions of records, well you’ll quickly find the limit with your computer memory.

And that’s where iterators comes: they’re able to solve those two problems. How? Well that’s pretty simple. To fully work, a classic

--

--

Alexandre Daubois
Geek Culture

Lead Developer at Wanadev // Open-source contributor