TExcelTAD
Home › PHP › PHP Iterables

PHP Iterables

Anything you can loop over with foreach is an iterable. In PHP that means two things: plain arrays, and objects that implement the Traversable interface (which includes generators and your own iterator classes). The iterable pseudo-type lets a function accept either one.

The iterable type

php · try it yourself
<?php
function total(iterable $numbers): int
{
    $sum = 0;
    foreach ($numbers as $n) {
        $sum += $n;
    }
    return $sum;
}

echo total([1, 2, 3]), "\n";
echo total(new ArrayIterator([10, 20, 30])), "\n";

var_dump(is_iterable([1]));
var_dump(is_iterable("text"));
6
60
bool(true)
bool(false)

Since PHP 8.2, iterable is simply an alias for the union type array|Traversable.

Generators: the easy way to make an iterable

A generator is a function that uses yield instead of (or as well as) return. Calling it does not run the body; it returns a Generator object. Each time foreach asks for the next value, the function runs until the next yield and pauses there.

php · try it yourself
<?php
function countdown(int $from): Generator
{
    echo "(starting)\n";
    for ($i = $from; $i > 0; $i--) {
        yield $i;
    }
    echo "(finished)\n";
}

$gen = countdown(3);
echo "Generator created\n";

foreach ($gen as $n) {
    echo "T-minus $n\n";
}
Generator created
(starting)
T-minus 3
T-minus 2
T-minus 1
(finished)

Notice that "(starting)" appears only after the loop begins — the work is lazy.

Keys and memory

yield $key => $value produces keys as well. Because generators compute one value at a time, they can walk through huge (even infinite) sequences using almost no memory.

php · try it yourself
<?php
function squares(): Generator
{
    $n = 1;
    while (true) {          // infinite, but lazy
        yield $n => $n * $n;
        $n++;
    }
}

foreach (squares() as $n => $square) {
    if ($square > 50) {
        break;
    }
    echo "{$n}² = $square\n";
}

function letters(): Generator
{
    yield 'a';
    yield 'b';
    yield from ['c', 'd'];   // delegate to another iterable
}

echo implode(",", iterator_to_array(letters(), false)), "\n";
1² = 1
2² = 4
3² = 9
4² = 16
5² = 25
6² = 36
7² = 49
a,b,c,d

Tip: iterator_to_array($it, false) collects an iterable into a normal list. Pass false so duplicate keys (common with yield from) don't overwrite each other.

The Iterator interface

For full control, a class can implement Iterator and its five methods. foreach calls them in this order:

Method Purpose
rewind() Go back to the first element (called once, at the start)
valid() Is there a current element? Loop stops when this is false
current() Return the current value
key() Return the current key
next() Move to the next element
php · try it yourself
<?php
class Range implements Iterator
{
    private int $current;

    public function __construct(private int $start, private int $end, private int $step = 1) {}

    public function rewind(): void { $this->current = $this->start; }
    public function valid(): bool { return $this->current <= $this->end; }
    public function current(): mixed { return $this->current; }
    public function key(): mixed { return ($this->current - $this->start) / $this->step; }
    public function next(): void { $this->current += $this->step; }
}

foreach (new Range(10, 30, 5) as $index => $value) {
    echo "$index => $value\n";
}
0 => 10
1 => 15
2 => 20
3 => 25
4 => 30

IteratorAggregate: delegate the work

Writing five methods is often overkill. With IteratorAggregate you implement just one method, getIterator(), and return any Traversable — usually an ArrayIterator or a generator.

php · try it yourself
<?php
class TeamRoster implements IteratorAggregate, Countable
{
    private array $members = [];

    public function add(string $name, string $role): void
    {
        $this->members[$name] = $role;
    }

    public function getIterator(): Generator
    {
        ksort($this->members);
        foreach ($this->members as $name => $role) {
            yield $name => strtoupper($role);
        }
    }

    public function count(): int
    {
        return count($this->members);
    }
}

$team = new TeamRoster();
$team->add("Zoe", "designer");
$team->add("Anh", "developer");
$team->add("Marco", "tester");

echo count($team), " members\n";
foreach ($team as $name => $role) {
    echo str_pad($name, 6), $role, "\n";
}
3 members
Anh   DEVELOPER
Marco TESTER
Zoe   DESIGNER

The class keeps its array private, yet callers can still loop over it — in a sorted, formatted way the class controls.

Which one should I use?

Need Use
Accept arrays or iterators as a parameter iterable type
Produce values lazily, compute on the fly Generator (yield)
Make a collection object loopable IteratorAggregate
Fine-grained control over each step Iterator

Note: A generator can be iterated only once. Looping over the same Generator object a second time throws an exception. Call the generator function again to get a fresh one.

Test yourself

Which values satisfy the iterable type?

  1. Only arrays
  2. Arrays and Traversable objects
  3. Any object
  4. Strings and arrays

When does the body of a generator function start running?

  1. Immediately when it is called
  2. When the first value is requested
  3. Only after return
  4. When the script ends

How many methods must a class implement for IteratorAggregate?

  1. One: getIterator()
  2. Two
  3. Five
  4. None