Skip to main content

PHP Iterables

An iterable in PHP is any value you can walk through with a foreach() loop.

PHP 7.1 added iterable as a pseudo-type, which you can use for function arguments and return values.

Two kinds of values qualify: arrays, and objects that implement the Iterator interface.


PHP - Using Iterables

Write iterable as the type of a function parameter or as the function's return type:

Example

A function that accepts an iterable parameter, called once with an array and once with an object:

Prompt
Create a PHP function called printIterable that takes an iterable parameter and echoes each item. Call it with an array ["a", "b", "c"] and also with an ArrayIterator object containing ["d", "e", "f"].
Output: PHP script

Example

A function whose return type is iterable:

Prompt
Create a PHP function called getIterable that has an iterable return type and returns an array ["a", "b", "c"]. Use a foreach loop to echo each item from the returned iterable.
Output: PHP script

PHP - Creating Iterables

Every array is an iterable, so you can pass any array to a function that expects one.

The same goes for objects: any object that implements Iterator is accepted too.

An iterator holds a list of items and gives you methods for moving through them. It keeps a pointer on one element of the list at a time, and each item should have a key that can be used to locate it.

Your iterator has to define these five methods:

  • current() - Gives back the element under the pointer, which can be of any data type
  • key() - Gives back the key of the current element, which can only be an integer, float, boolean or string
  • next() - Advances the pointer by one element
  • rewind() - Sends the pointer back to the first element
  • valid() - Returns true as long as the internal pointer is on an element. It should return false when the pointer is on no element, such as after next() was called at the end of the list

Example

Here, a class implements Iterator, and its object is then passed to a function as an iterable:

Prompt
Create a PHP class called MyIterator that implements the Iterator interface with methods current(), key(), next(), rewind(), and valid(). Then create a function printIterable() that loops through an iterable and echoes each item. Use MyIterator with items ["a", "b", "c"].
Output: PHP script