Author: Samuel Adeshina
Last month viewers: 1
Categories: PHP opinions
Read this opinion article to understand why using iterators is a better idea than using loops in PHP.
Foreach, for and while loops have turned into the defacto standard for doing "iteration" in PHP, making it impossible for self-taught, "I'm a beginner in the PHP ecosystem" kind of programmers (or developers) to understand that they are inefficient "iterators for every use-case" and are not even meant for iterating at all, they are just looping functions and that is what they should be used for, loops.
Recently, I was going through a program written by somebody I know. He needed to iterate over a multi dimensional array that contains over 100 entries to wrap each of those entries with brackets, he used a for loop inside a for loop and had a very lengthy run of 'his algorithm'.
That was bad. I wish he knew PHP has an `IteratorIterator` class specifically meant for doing this, I wish he knew theres even a more interesting solution, a `RecursiveIteratorIterator` class. I wish he knew there is a difference between looping through an array and iterating over it or even more better, I wish he knew there is a very huge difference between iteration and looping.
Most of the time, we get confused (or too lazy). We use loops for every use case and then keep wondering why the value of our php.ini max_execution_time variable has to be increased for PHP to stop showing those heartbreaking "fatal errors".
I have written this to establish a line in our minds, a line every PHP introductory material never draws.
Never loop through a problem that should be solved by Iteration.
I'd recommend to iterate (a little pun intended) over each of the links below, they might help to paint over the lines I've just drawn in your minds (at least I hope so) and make that line stay forever.
- A Quora question/answer about the difference between a loop and an iterator
- A nice presentation introducing PHP iterators
- A list of 'built in iterators', really really useful place to start learning about what PHP actually offers you.
- An even more interesting way to do iteration, using generators.
You need to be a registered user or login to post a comment
1,582,490 PHP developers registered to the PHP Classes site.
Be One of Us!
Login Immediately with your account on: