In PHP, an iterable is any value that can be looped through with a foreach
loop. Iterables provide a convenient way to work with collections of data, such as arrays and objects implementing the Traversable interface.
Iterables are essential for processing collections of data efficiently. They allow you to iterate over elements without needing to know the internal structure of the collection. This abstraction simplifies code and improves flexibility.
The most common way to work with iterables is through the foreach
loop. This construct allows you to iterate over each element in the collection easily.
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
This code will output each fruit on a new line.
For objects, you need to implement the Iterator interface or use generators to make them iterable.
class FruitBasket implements Iterator {
private $fruits = ["apple", "banana", "cherry"];
private $position = 0;
public function current() {
return $this->fruits[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function rewind() {
$this->position = 0;
}
public function valid() {
return isset($this->fruits[$this->position]);
}
}
$basket = new FruitBasket();
foreach ($basket as $fruit) {
echo $fruit . "\n";
}
PHP 7.1 introduced the iterable type hint, allowing you to specify that a function parameter or return value should be iterable.
function printItems(iterable $items) {
foreach ($items as $item) {
echo $item . "\n";
}
}
$array = [1, 2, 3];
printItems($array);
To deepen your understanding of PHP iterables and related topics, explore these concepts:
Mastering iterables in PHP will enhance your ability to work with collections efficiently, leading to more elegant and maintainable code.