SPL Iterators
An iterator is an object that walks through values one step at a time. ArrayIterator wraps a plain array for that walk, and other iterators can reshape the walk.
An object walks like an array
ArrayIterator wraps the numbers 5, 15 and 25 here. foreach walks the object and prints each value in order.
<?php
$it = new ArrayIterator([5, 15, 25]);
foreach ($it as $value) {
echo $value . "\n";
}A limit walks a window
LimitIterator wraps the ArrayIterator here with offset 1 and count 2. The walk skips 10 and stops after two values.
<?php
$it = new ArrayIterator([10, 20, 30, 40]);
$window = new LimitIterator($it, 1, 2);
foreach ($window as $value) {
echo $value . "\n";
}Keys ride along in the walk
The wrapped array here pairs each name with a value. foreach reads each key beside its value and prints both.
<?php
$it = new ArrayIterator(["name" => "Hana", "city" => "Oslo"]);
foreach ($it as $key => $value) {
echo $key . " => " . $value . "\n";
}Example
<?php
$list = new ArrayIterator(["cover", "toc", "start", "middle", "end"]);
$page = new LimitIterator($list, 2, 2);
foreach ($page as $item) {
echo $item . "\n";
}Key points
- ArrayIterator wraps a plain array in an object.
- foreach can walk an ArrayIterator in the same way it walks a plain array.
- The keys of the wrapped array ride along during the walk.
- LimitIterator takes an iterator and walks only a slice of it.
- LimitIterator takes a starting offset and a count of values.
In this example, the list wraps five fixed items in an ArrayIterator. LimitIterator starts at offset 2, so it skips cover and toc. The walk then prints the next two items, start and middle.
Note
The wrapped array stays unchanged when a LimitIterator walks only part of it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A LimitIterator with offset 1 and count 2 walks the values 10, 20, 30 and 40. Which value prints first?