What is the Iterator interface in PHP, and how does it relate to how a foreach loop actually works behind the scenes?
Short answer
The Iterator interface defines a set of methods, including current, key, next, rewind, and valid, that a class must implement to define exactly how it should be iterated over, and PHP's foreach loop automatically calls these methods in the correct sequence when looping over any…
Advertisement
AModel answer
The Iterator interface defines a set of methods, including current, key, next, rewind, and valid, that a class must implement to define exactly how it should be iterated over, and PHP's foreach loop automatically calls these methods in the correct sequence when looping over any object implementing this interface, meaning you can make your own custom class behave just like a native array when used in a foreach loop.
class NumberCollection implements Iterator {
private $items = [1, 2, 3];
private $position = 0;
public function current(): mixed { return $this->items[$this->position]; }
public function key(): mixed { return $this->position; }
public function next(): void { $this->position++; }
public function rewind(): void { $this->position = 0; }
public function valid(): bool { return isset($this->items[$this->position]); }
}Real-world example
A custom collection class implements the Iterator interface so that developers using it can simply loop over an instance with a familiar foreach statement, without needing to know anything about its internal storage structure.
Likely follow-ups
- How does a generator relate to the Iterator interface internally?
- What is the simpler IteratorAggregate interface and how does it differ from implementing Iterator directly?
Related topics