php8.5
Home/ Manual/ language / predefined/ The Iterator interface

The Iterator interface

Interface for external iterators or objects that can be iterated themselves internally.

Intro

Interface for external iterators or objects that can be iterated themselves internally.

Interfacesynopsis

implements Iterator extends Traversable { }

Predefined iterators

PHP already provides a number of iterators for many day-to-day tasks. See SPL iterators for a list.

Examples

Basic usage

This example demonstrates in which order methods are called when using Foreach with an iterator.

php
<?php
class myIterator implements Iterator {
    private $position = 0;
    private $array = array(
        "firstelement",
        "secondelement",
        "lastelement",
    );  

    public function __construct() {
        $this->position = 0;
    }

    public function rewind(): void {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    #[\ReturnTypeWillChange]
    public function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    #[\ReturnTypeWillChange]
    public function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    public function next(): void {
        var_dump(__METHOD__);
        ++$this->position;
    }

    public function valid(): bool {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}

$it = new myIterator;

foreach($it as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

The above example will output something similar to:

output
string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

See Also

See also object iteration.

Current Key Next Rewind Valid

In this section

Source: language/predefined/iterator.xml · from the official PHP manual (php/doc-en)