Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

IteratorAggregate

The interface of objects that can be looped over with `foreach`.

Syntax

class Name implements IteratorAggregate

Return value

TraversableThe `getIterator()` method returns an iterator or a generator.

Examples

Iterating through a generator:

<?php
 
class Team implements IteratorAggregate
{
    public function __construct(private array $members) {}
 
    public function getIterator(): Generator
    {
        yield from $this->members;
    }
}
 
foreach (new Team(['Anna', 'Oleg']) as $index => $name) {
    echo $index, ': ', $name, "\n";
}

Output:

0: Anna
1: Oleg

Notes

This is the shortest way to make an object iterable. The Iterator interface is needed only when iteration must be controlled by hand.

See also

  • Iterator — An interface with five methods for controlling iteration by hand.
  • Generator — The object returned by a function containing `yield`.
  • iterator_to_array — Turns an iterator or a generator into an array.

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.