PHP Iterables

PHP Iterables

An iterable is any value which can be looped through using a foreach() loop.

The iterable pseudo-type was introduced in PHP 7.1. It can be used as a data type for function arguments or return types to guarantee that the data passed in or out can be safely iterated.


Using the Iterable Type

By typing a parameter as iterable, you ensure that the function accepts either an Array or an Object that implements the Traversable interface.

If a standard integer, string, or non-traversable object is passed to the function, PHP will throw a strict Type Error.

Iterable Example

<?php
// The function demands that the input is iterable
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item . " ";
  }
}

$arr = ["a", "b", "c"]; printIterable($arr); // Arrays are inherently iterable ?>

Why Iterables?

In complex OOP applications, you often create custom objects (like a UserList collection) that store data inside private arrays. By making your UserList class implement the Iterator interface, it becomes an iterable.

This allows other developers to pass your custom UserList object directly into a foreach loop as if it were a simple array!