PHP Iterables
PHP Iterables
In PHP, an iterable is a value that can be looped through with aforeach() loop.
Theiterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and functionreturn values.
An iterable can be an array or an object that implements theIterator interface.
PHP - Using Iterables
Theiterable keyword can be used as a data type of a function parameter or as the returntype of a function:
Example
An iterable function parameter:
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
An iterable return type:
function getIterable():iterable {
return ["a", "b", "c"];
}
foreach(getIterable() as $item) {
echo $item;
}
?>
PHP - Creating Iterables
Arrays
All arrays are iterables, so any array can be used as an argument of a function that requires an iterable.
Iterators
Any object that implements theIterator interface can be used as an argument of a functionthat requires an iterable.
An iterator contains a list of items and provides methods to loop through them. It keeps apointer to one of the elements in the list. Each item in the list should have a key which canbe used to find the item.
An iterator must have these methods:
current()- Returns the element that the pointer is currently pointing to. It can be anydata typekey()Returns the key associated with the current element in the list. It can only bean integer, float, boolean or stringnext()Moves the pointer to the next element in the listrewind()Moves the pointer to the first element in the listvalid()If the internal pointer is not pointing to any element (for example, if next()was called at the end of the list), this should return false. It returns true in anyother case
Example
Implement the Iterator interface and use it as an iterable:
// 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);
?>

