Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

Iterator

An interface with five methods for controlling iteration by hand.

Syntax

class Name implements Iterator

Return value

IteratorThe `current()`, `key()`, `next()`, `rewind()` and `valid()` methods.

Examples

A range of numbers with a step:

<?php
 
class Steps implements Iterator
{
    private int $value;
 
    public function __construct(private int $from, private int $to, private int $step) {}
 
    public function rewind(): void { $this->value = $this->from; }
    public function valid(): bool { return $this->value <= $this->to; }
    public function current(): int { return $this->value; }
    public function key(): int { return ($this->value - $this->from) / $this->step; }
    public function next(): void { $this->value += $this->step; }
}
 
foreach (new Steps(10, 30, 10) as $key => $value) {
    echo $key, '=', $value, ' ';
}

Output:

0=10 1=20 2=30

Notes

foreach calls the methods in this order: rewind(), then on every step valid(), current(), key() and next(). A generator does the same far more briefly.

See also

  • IteratorAggregate — The interface of objects that can be looped over with `foreach`.
  • Generator — The object returned by a function containing `yield`.
  • current — Returns the element the array's internal pointer points to.

In the tutorial

  • Built-in interfaces — PHP interfaces that teach an object to behave like an array — Countable, IteratorAggregate, ArrayAccess, JsonSerializable and Stringable.

Thanks for reading!

Donate to the site — we work hard for you.