PHP Iterable interface

The Iterator interface extends the abstract Traversable interface in PHP. It allows user-defined classes to become iterable using foreach loops. PHP provides many built-in iterators (called SPL iterators) like ArrayIterator, DirectoryIterator, etc. A user class implementing the Iterator interface must implement all its abstract methods.

Syntax

Iterator extends Traversable {
   /* Methods */
   abstract public current ( void ) : mixed
   abstract public key ( void ) : scalar
   abstract public next ( void ) : void
   abstract public rewind ( void ) : void
   abstract public valid ( void ) : bool
}

Methods

The Iterator interface requires implementing these five methods ?

  • current() − Return the current element
  • key() − Return the key of the current element
  • next() − Move forward to next element
  • rewind() − Rewind the Iterator to the first element
  • valid() − Checks if current position is valid

Example

Here's a complete example of a class implementing the Iterator interface ?

<?php
class myIterator implements Iterator {
   private $index = 0;
   private $arr = array(10,20,30,40);
   
   public function __construct() {
      $this->index = 0;
   }
   
   public function rewind() {
      $this->index = 0;
   }
   
   public function current() {
      return $this->arr[$this->index];
   }
   
   public function key() {
      return $this->index;
   }
   
   public function next() {
      ++$this->index;
   }
   
   public function valid() {
      return isset($this->arr[$this->index]);
   }
}

// Using foreach loop
$it = new myIterator();
foreach($it as $key => $value) {
   echo "$key=>" . $value . "<br>";
}

echo "<br>";

// Using manual iteration
$it->rewind();
do {
   echo $it->key() . "=>" . $it->current() . "<br>";
   $it->next();
}
while ($it->valid());
?>
0=>10
1=>20
2=>30
3=>40

0=>10
1=>20
2=>30
3=>40

How It Works

When using foreach on an Iterator object, PHP automatically calls ?

  1. rewind() − Reset to beginning
  2. valid() − Check if current position exists
  3. current() and key() − Get current value and key
  4. next() − Move to next position
  5. Repeat steps 2-4 until valid() returns false

Conclusion

The Iterator interface provides a standardized way to make custom classes iterable with foreach loops. By implementing the five required methods, you can control exactly how your objects are traversed.

Updated on: 2026-03-15T09:24:47+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements