In PHP, the Iterator interface allows objects to be traversed like arrays. By implementing its five methods, an object can be used with the foreach construct to loop through its internal elements in a clean and structured way.
The Iterator interface defines the following methods:
Several built-in PHP classes such as ArrayIterator, SplDoublyLinkedList, and RecursiveIteratorIterator implement this interface, making them directly usable in a foreach loop.
Arrays in PHP natively support iteration with the foreach loop. Here’s a basic example:
$arr = array('a', 'b', 'c');
foreach ($arr as $key => $value) {
echo "$key: $value\n";
}
This approach provides a clean way to loop through arrays without manually managing indexes or element access.
You can also create your own class that implements the Iterator interface, allowing its objects to be iterated over using foreach. Here’s an example implementation:
class MyIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
);
public function __construct() {
$this->position = 0;
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->array[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->array[$this->position]);
}
}
$it = new MyIterator;
foreach ($it as $key => $value) {
echo "$key: $value\n";
}
In this example, the MyIterator class encapsulates an array and tracks the current position with a private property. Implementing all five methods ensures that the object is fully traversable using foreach, just like a regular array.
The Iterator interface offers a standardized way to loop through object properties in PHP. Whether you're working with arrays, built-in collection classes, or custom objects, implementing this interface makes your data structures compatible with foreach. This results in cleaner, more maintainable, and more flexible code structures.