# The `Iterable` Type

> Section in “New and Extended Functionality › Type System” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/type-system/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`:

``` php
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:

``` php
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:

``` php
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)

---

Previous: [The object Type](https://php7explained.com/new-and-extended-functionality/type-system/the-object-type/index.html.md) | Next: [Type Casting to array or object](https://php7explained.com/new-and-extended-functionality/type-system/type-casting-to-array-or-object/index.html.md)
