PHP Reference ยท Standard PHP Library and Classes
The Iterator and IteratorAggregate interfaces
Reference for PHP Iterator and IteratorAggregate: make your own objects work with foreach, the call order of the five methods, generators in getIterator() and common mistakes.
An object can be used in foreach when it implements Traversable. You never implement Traversable yourself; you choose one of its two child interfaces. Iterator gives you full control through five methods. IteratorAggregate needs one method, getIterator(), which hands back some other iterator and is the better choice most of the time.
Without either interface, foreach over an object walks its public properties, which exposes internals and changes whenever the class does.
<?php final class Numbers implements IteratorAggregate { public function getIterator(): Generator { yield 1; yield 2; } } foreach (new Numbers() as $n) { echo $n; }
Try it
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.
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
interface Iterator extends Traversable { public function current(): mixed; public function key(): mixed; public function next(): void; public function rewind(): void; public function valid(): bool; } interface IteratorAggregate extends Traversable { public function getIterator(): Iterator; }
| Method | Called | Purpose |
|---|---|---|
rewind() |
Once, at the start of the loop | Reset to the first element. |
valid() |
Before every iteration | Return false to end the loop. |
current() |
After valid() returned true |
The value for $value. |
key() |
After current(), if the loop asks for keys |
The key for $key. |
next() |
After each loop body | Move to the following element. |
getIterator() |
Once per foreach |
Return an Iterator (a generator is one). |
Return value: getIterator() must return an Iterator or a Traversable object; a generator method is the shortest way to write it.
Errors / Exceptions: returning something that is not traversable from getIterator() throws an exception when the loop starts.
Usage notes
- Prefer
IteratorAggregatewith a generator. It is short and eachforeachgets a fresh, independent iterator, so nested and repeated loops work. - Write an
Iteratorby hand only when you need external control over the cursor, cheap rewinding, or lazy loading you cannot express withyield. - A generator is itself an
Iterator, but it can be traversed only once. Rewinding it after the first element has been produced throws an exception. - State lives in the iterator. An object that implements
Iteratorhas one cursor, so two simultaneous loops over it will interfere. That is a reason to useIteratorAggregate. - Keys can be anything when you yield them yourself (strings, floats, objects) but
iterator_to_array()needs scalar keys; passfalseas the second argument to keep only values. - Helper functions:
iterator_to_array(),iterator_count()anditerator_apply()work on anyTraversable.iterableas a type accepts arrays and traversables alike. - Delegation:
yield from $other;forwards another iterable's values from insidegetIterator(). - Return types: since PHP 8.1, omitting the return types on the five methods triggers a deprecation notice; declare them.