Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Standard PHP Library and Classes

SPL iterators

Reference for PHP SPL iterators: ArrayIterator, LimitIterator, CallbackFilterIterator, RecursiveArrayIterator, RecursiveIteratorIterator, AppendIterator and more, with examples.

The Standard PHP Library ships a family of ready-made iterators. Most of them are decorators: you wrap one iterator (or an array or generator) in another that changes how it is traversed, such as stopping after N items, skipping some, or walking nested data. Because each one is itself an Iterator, you can stack them and use the result in foreach.

These classes work lazily, one element at a time, so they suit large data. Arrays are wrapped with ArrayIterator; generators need IteratorIterator or new NoRewindIterator() in some cases because they cannot rewind.

Try it

PHP Limit, filter and chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Walking nested arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
new ArrayIterator(array|object $array = [], int $flags = 0)
new LimitIterator(Iterator $iterator, int $offset = 0, int $limit = -1)
new CallbackFilterIterator(Iterator $iterator, callable $callback)
new RecursiveIteratorIterator(Traversable $iterator, int $mode = RecursiveIteratorIterator::LEAVES_ONLY, int $flags = 0)

The common classes:

Class What it does
ArrayIterator Iterates over an array or the public properties of an object; supports count(), array access and sorting.
IteratorIterator Wraps any Traversable so it can be used as an Iterator (for example a generator or IteratorAggregate).
LimitIterator Yields limit items starting at position offset. Throws OutOfBoundsException for an offset beyond the data on seekable iterators.
CallbackFilterIterator Keeps items for which the callback ($current, $key, $iterator) returns true.
RegexIterator Filters (or maps) values with a regular expression.
AppendIterator Runs several iterators one after another.
MultipleIterator Walks several iterators in parallel, yielding arrays.
InfiniteIterator Restarts the inner iterator when it ends; always combine with LimitIterator.
NoRewindIterator Ignores rewind() so a one-shot source is consumed only once.
CachingIterator Looks one element ahead; hasNext() tells whether more follow.
RecursiveArrayIterator Like ArrayIterator, but exposes nested arrays as children.
RecursiveIteratorIterator Flattens a recursive iterator. Modes: LEAVES_ONLY (default), SELF_FIRST, CHILD_FIRST. getDepth() gives the nesting level.
EmptyIterator Yields nothing.

Return value: constructors create the iterator; iterator_to_array($it, false) collects the values into a list and iterator_count() counts them.

Usage notes

  • Keys can repeat. Flattening or appending often yields duplicate keys; pass false as the second argument of iterator_to_array() or the later items overwrite the earlier ones.
  • Filters keep the original keys. Filtering range(1, 10) keeps keys 1, 3, 5 and so on, as the $key=>$value output shows.
  • LimitIterator after filtering counts filtered items, not source items. Order matters when you stack decorators.
  • Generators cannot rewind. Wrap them carefully; looping twice over a generator throws Exception.
  • Recursive modes. LEAVES_ONLY skips arrays themselves; SELF_FIRST visits the container before its children, which is what you need to print a tree.
  • Many are cheaper than arrays, since nothing is copied, but a simple foreach over a generator is often clearer than three nested decorators.
  • File-related iterators such as DirectoryIterator, RecursiveDirectoryIterator and SplFileObject follow the same Iterator protocol, so every decorator above works on them.