What is an Iterable in PHP?

Recall the loops tutorial in this PHP series and get to the foreach loop to be exact. In this article, you will learn iterables in PHP in link with foreach loop.

  • Iterables is any value that foreach loop accept and is iterable.
  • PHP 7.1 introduced this pseudo-data type and it can be used as return data type of functions. Also, function can accept iterables as its argument.

How to use Iterables in PHP?

iterable keyword defines the type of the argument or return type of the function should be an iterable value. Look at the following example.

Example

<?php
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

$arr = ["a", "b", "c"];
printIterable($arr);
?>
  • In the above example. we create a function that accept some argument. We specify the argument must be iterable using iterable keyword.
  • Now, if we call this function and pass non-iterable value as the argument of the function, it will throw an error.
  • So, iterables make sure to feed an iterable value to the foreach loop inside a function. Think and try to pass non-iterable value to the foreach loop and check what happens. Thn, you should be more clear about the use of iterables.

Example – Function returning Iterable

In the above example, we studied the iterable as an argument of the function, now, we will see the iterable as the return value from a function.

<?php
function getIterable():iterable {
  return ["a", "b", "c"];
}

$myIterable = getIterable();
foreach($myIterable as $item) {
  echo $item;
}
?>
  • In the above example, we create a function that simple return some value. Focus on the return type of the function on the right side of the function name iterable. It makes it mandatory for the function to return iterable value.
  • Call the function and pass the returned value to the foreach loop. Try to run this example on your machine and see what echo prints on the screen.
  • Try to practice this example by returning some non-iterables value out of the function. Read the error and then return some single and two-dimensional arrays.

How to create Iterables in PHP?

  • Arrays: All arrays in PHP are iterables. As in the beggining of this read, you leanred that any data that foreach loop can accept is iterable. So, all the single , multi-dimensional, and associative arrays are iterables by default.
  • Iterators: An object implemented iterator interface is aslo accepted by a function that requires iterable data in argument.

An iterator consists of the data to loop on it and methods that work together to loop through the data. A pointer always points at an element of the data. Each element of the data contains a key which is used to find each element inside the data of the iterable.

To make an iterator, it should implement the following methods.

  • next() – Moves the pointer to the next element in the data.
  • rewind() – The pointer starts pointing at the first element of data.
  • valid() – It makes sure that the pointer is pointing to its desired element or not. For example, if the next() is called and the pointer is at last element of the data i:e not data element exist after it. Then valid will return false. It will return true when the next() moves to the next element and rewind() moves to the first element.

Example

Creating iterable by implementing iterator interface and then using it as an iterable.

<?php
// Create an Iterator
class MyIterator implements Iterator {
  private $items = [];
  private $pointer = 0;

  public function __construct($items) {
    // array_values() makes sure that the keys are numbers
    $this->items = array_values($items);
  }

  public function current() {
    return $this->items[$this->pointer];
  }

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

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

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

  public function valid() {
    // count() indicates how many items are in the list
    return $this->pointer < count($this->items);
  }
}

// A function that uses iterables
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

// Use the iterator as an iterable
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>