What is an Iterable in PHP?
A value that can be looped through with a foreach() loop is called a \”iterable.\”
PHP 7.1 added the iterable pseudo-type, which can be used as a data type for function arguments and function return values.
Example
<!DOCTYPE html>
<html>
<body><?php
function testIterable():iterable {
return [\”x\”, \”y\”, \”z\”];
}$varIterable = testIterable();
foreach($varIterable as $item) {
echo $item;
}
?></body>
</html>
Output
xyz
PHP: How to Use Iterables
The iterable keyword can be used as an argument data type or as a function\’s return type:
PHP: How to Make Iterables
Arrays
All arrays are iterables, which means that any array can be passed to a function that needs an iterable as an argument.
Iterators
A function that needs an iterable can take as an argument any object that implements the Iterator interface.
An iterator has a list of items and ways to go through them in a loop. It keeps track of a pointer to one of the list\’s items. Each thing on the list should have a key that lets you find it.
This is what an iterator must have:
- current() gives back the element that the pointer is currently pointing to. It can be any kind of data.
- key() gives back the key that goes with the current list item. It can only be a number, a string, a float, or a boolean.
- next() moves the list pointer to the next item.
- rewind() moves the list pointer to the first item.
- valid() should return false if the internal pointer doesn\’t point to any element. This could happen if next() was called at the end of the list. It comes back true in all other situations