PHP Iterables
In PHP, an iterable is a data type that can be looped through with a foreach
loop or other iteration methods. PHP defines iterables as arrays and objects that implement the Traversable
interface.
Here’s a quick rundown of how you can work with iterables in PHP:
Arrays
Arrays are the most common form of iterables in PHP. You can easily loop through them using foreach
.
Example:
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
Output:
apple
banana
cherry
Objects
To make an object iterable, it must implement the Traversable
interface. There are two interfaces that extend Traversable
: Iterator
and IteratorAggregate
.
1. Using Iterator
Interface
Implementing the Iterator
interface requires defining the following methods: current()
, key()
, next()
, rewind()
, and valid()
.
Example:
class MyIterator implements Iterator {
private $items = [];
private $index = 0;
public function __construct($items) {
$this->items = $items;
}
public function current() {
return $this->items[$this->index];
}
public function key() {
return $this->index;
}
public function next() {
++$this->index;
}
public function rewind() {
$this->index = 0;
}
public function valid() {
return isset($this->items[$this->index]);
}
}
$iterator = new MyIterator(["apple", "banana", "cherry"]);
foreach ($iterator as $fruit) {
echo $fruit . "\n";
}
Output:
apple
banana
cherry
2. Using IteratorAggregate
Interface
IteratorAggregate
is a simpler way to make an object iterable. You only need to implement the getIterator()
method which should return an instance of Traversable
(like an ArrayIterator
).
Example:
class MyIterable implements IteratorAggregate {
private $items = [];
public function __construct($items) {
$this->items = $items;
}
public function getIterator() {
return new ArrayIterator($this->items);
}
}
$iterable = new MyIterable(["apple", "banana", "cherry"]);
foreach ($iterable as $fruit) {
echo $fruit . "\n";
}
Output:
apple
banana
cherry
Conclusion
In summary, PHP iterables can be arrays or objects that implement the Traversable
interface. Arrays are the simplest form, but you can also create custom iterable objects by implementing Iterator
or IteratorAggregate
. This flexibility allows you to control how objects are iterated over, making PHP a powerful language for handling different types of data collections.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.