I was perusing the manual today and noticed the various iterators. To me, it seems like they are all somewhat pointless; I don’t see a reason to use them unless you prefer their syntax, or don’t know how to write a recursive function. Are there any reasons to use built-in iterators in PHP over just writing a loop or making a recursive method?
I’m only looking for factual responses, not subjective preferences (ie: I don’t care if you think it’s more "readable" or "more object-oriented", I want to know if they’re faster, offer functionality that can’t be achieved when rolling your own, etc.).
I believe the main reason is versatility. They don’t make things more readable and you can accomplish most of what the spl iterators do with a simple
foreach.But iterators can serve as sort of a compacted loop or loop source that you can pass around. You can have more diverse data sources than just a list/array. And the real advantage is that you can wrap or stack them for aggregation.
The naming is somewhat unobvious, but I guess you could use the
AppendIteratorto for example combine a static list of filenames and the result of aDirectoryIterator. Or otherwise wrap that in aLimitIteratorinstead of hardwiring that into aforcondition. All of these are pretty basic features and can be done manually in a foreach. But at leastRegexIteratorandFilterIteratorseem suitable to reduce some complexity.But in the end it’s really a stylistic choice. It would make most sense if you have custom objects which traverse something (for example a VFS object which can either point to real files or database entries). But even then you could just
iterator_to_arrayconvert such a list, and use a normalforeach-over-array.The only case were it is really imperative to prefer iterators were if the data source is unlimited in size. Unfolded arrays for use in a
foreachcan consume more memory than an iterator which can retrieve element by element.