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:
Output: PHP script
<?php
function printIterable(iterable $x) {
foreach($x as $item) {
echo $item;
}
}
// Called with an array:
printIterable(["a", "b", "c"]);
// Called with an object:
$iterator = new ArrayIterator(["d", "e", "f"]);
printIterable($iterator);
?>
Example
A function whose return type is iterable:
Output: PHP script
<?php
function getIterable():iterable {
return ["a", "b", "c"];
}
foreach(getIterable() as $item) {
echo $item;
}
?>
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 typekey()- Gives back the key of the current element, which can only be an integer, float, boolean or stringnext()- Advances the pointer by one elementrewind()- Sends the pointer back to the first elementvalid()- 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 afternext()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:
Output: PHP script
<?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);
?>