PHP Iterable interface


Introduction

Iterator interface extends abstract Traversable interface. PHP provides many built-in iterators (called SPL iterators) for many routine functionalities. Examples are ArrayIterator, DirectoryIterator etc. A user class that implements Iterator interface should implement abstract methods as defined in it.

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

Iterator::current — Return the current element

Iterator::key — Return the key of the current element

Iterator::next — Move forward to next element

Iterator::rewind — Rewind the Iterator to the first element

Iterator::valid — Checks if current position is valid

When implementing IteratorAggregate or Iterator interface which extends Traversable, they must be listed before its name in the implements clause.

Iterator Example

In following PHP script, a class that implements Interface contains an array as private variable. Implementing abstract methods of Iterator, we can traverse the array using foreach loop as well with next() method.

Example

<?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, we can iterate over array property of MyIterator object

$it = new myIterator();
foreach($it as $key => $value) {
   echo "$key=>". $value ."
"; }

Iteration can also be performed by clling next() method in a while loop. Make sure to rewind the iterator before commencing loop

Example

$it->rewind();
do {
   echo $it->key() . "=>" .$it->current() . "
";    $it->next(); } while ($it->valid());

Output

On both occasions, traversal of array property shows following result

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

Updated on: 21-Sep-2020

677 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements