The Iterable Type

What do arrays, generators, and iterators have in common? You can iterate over their elements. The iterable super-type allows for type declarations that accept an array as well as implementations of the Traversable interface such as generators (functions or methods that use the yield statement) and iterators (classes that implement the Iterator interface).

The example below shows that a function that expects a parameter of type iterable accepts an array:

function f(iterable $elements)
{
    foreach ($elements as $element) {
        var_dump($element);
    }
}

f([0, 1, 2]);

Executing the code shown above will print the output shown below:

int(0)
int(1)
int(2)

The example below shows that a function that expects a parameter of type iterable accepts a generator:

function g()
{
    yield 0;
    yield 1;
    yield 2;
}

function f(iterable $elements)
{
    foreach ($elements as $element) {
        var_dump($element);
    }
}

f(g());

Executing the code shown above will print the output shown below:

int(0)
int(1)
int(2)

The example below shows that a function that expects a parameter of type iterable accepts an object that implements the Iterator interface:

class MyIterator implements Iterator
{
    private $elements = [0, 1, 2];
    private $position;

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

    public function valid()
    {
        return $this->position < count($this->elements);
    }

    public function key()
    {
        return $this->position;
    }

    public function current()
    {
        return $this->elements[$this->position];
    }

    public function next()
    {
        $this->position++;
    }
}

function f(iterable $elements)
{
    foreach ($elements as $element) {
        var_dump($element);
    }
}

f(new MyIterator);

Executing the code shown above will print the output shown below:

int(0)
int(1)
int(2)