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 AppendIterator
to for example combine a static list of filenames and the result of a DirectoryIterator
. Or otherwise wrap that in a LimitIterator
instead of hardwiring that into a for
condition. All of these are pretty basic features and can be done manually in a foreach. But at least RegexIterator
and FilterIterator
seem 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_array
convert such a list, and use a normal foreach
-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 foreach
can consume more memory than an iterator which can retrieve element by element.