Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 147 ยท Advanced PHP

Iterators and the SPL

Make your PHP objects work with foreach, count() and [] using Iterator, IteratorAggregate, Countable and ArrayAccess, and use the SPL stacks, queues and heaps.

You can loop over an array with foreach, count it with count() and read an item with $items[2]. With a handful of built-in interfaces, your own objects can do the same. A Playlist, a ShoppingCart or a paginated set of database results can be looped over, counted and indexed while still hiding its internals and enforcing its own rules. Those interfaces are Iterator, IteratorAggregate, Countable and ArrayAccess.

They live alongside the Standard PHP Library (SPL), a collection of ready-made iterators and data structures that ships with every PHP installation: stacks, queues, priority queues, heaps, fixed-size arrays and object sets. This lesson shows how the interfaces work, when to pick each one, and which SPL classes are worth knowing. It builds on Generators, which turn out to be the easiest way to write an iterator.

How foreach works with objects

If you foreach over a plain object, PHP walks its visible properties. That's rarely what you want: it exposes internals and changes whenever the class changes.

PHP
<?php
final class Playlist
{
    public string $name = 'Road trip';
    private array $songs = ['Song A', 'Song B'];
}

foreach (new Playlist() as $key => $value) {
    echo "$key\n";   // prints only "name": private properties are hidden from outside code
}

An object that implements the Traversable interface tells foreach how to iterate it instead. You never implement Traversable directly; you implement one of its two children, Iterator or IteratorAggregate.

The Iterator interface

Iterator gives you full manual control through five methods that foreach calls in a fixed order:

Method Called when Returns
rewind() Once, before the loop starts nothing
valid() Before every iteration true to keep going, false to stop
current() When valid() was true the value for $value
key() When valid() was true (and you asked for a key) the value for $key
next() After each loop body nothing

The trace below makes the calling order visible:

PHP Implementing Iterator by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The sequence is rewind, then valid?, current, key, body, next for each item, and a final valid? that returns false. Because rewind() resets the state, you can loop over the same Countdown object as often as you like, unlike a generator.

Hand-written iterators are verbose, though. You'd write one when you need something unusual: a cursor that fetches the next page lazily, an iterator that can be rewound cheaply, or one that external code controls step by step with next().

IteratorAggregate: the easy way

Most of the time your object already holds its data in an array, or can produce it with a generator. Then implement IteratorAggregate and its single method, getIterator(), which returns any Iterator. A generator is the shortest option:

PHP IteratorAggregate with a generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Here getIterator() decides what iteration means: song numbers starting at 1 as keys and titles as values. The internal array keeps its own shape. Each foreach calls getIterator() again and gets a fresh generator, so the single-use limit of generators doesn't matter.

Implementing Countable adds a count() method that the built-in count($list) calls. Without it, count() on an object throws a TypeError.

Return ArrayIterator instead of a generator when you want callers to be able to count or seek within the iterator itself: return new ArrayIterator($this->songs);.

Type-hint parameters as iterable when a function only needs to loop. iterable accepts arrays and any Traversable, so callers can pass an array, a generator or one of your collection objects.

ArrayAccess: square brackets on objects

ArrayAccess lets code use $object[$key] syntax. It has four methods, one for each array operation:

Syntax Method called
isset($obj['x']), empty($obj['x']), $obj['x'] ?? ... offsetExists('x')
$obj['x'] offsetGet('x')
$obj['x'] = $v / $obj[] = $v offsetSet('x', $v) / offsetSet(null, $v)
unset($obj['x']) offsetUnset('x')

A good use is an array-like object that enforces rules. This settings object only accepts known keys and validates types:

PHP A validating settings object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last loop shows the payoff: the object refuses a string for fontSize, an unknown key, and $settings[] = ... (an append, which arrives as a null offset).

One limitation to know: offsetGet() returns a value, not a reference, so code like $settings['tags'][] = 'new' (modifying a nested array in place) doesn't work and PHP emits an "Indirect modification of overloaded element" notice. Objects with ArrayAccess are still objects, too. Functions such as array_map(), in_array() or sort() don't accept them. Use ArrayAccess for convenience syntax, not as a replacement for real arrays.

SPL data structures

PHP arrays are flexible enough to act as lists, stacks and queues, but the SPL gives you classes whose names and methods say what they are, and some of them are faster for their job.

SplStack and SplQueue

A stack is last in, first out (think undo history). A queue is first in, first out (think print jobs). Both are built on SplDoublyLinkedList:

PHP SplStack and SplQueue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With a plain array you'd use array_pop() for a stack and array_shift() for a queue. The catch is that array_shift() renumbers every remaining element, so it gets slower as the array grows; SplQueue::dequeue() takes the same short time no matter how long the queue is. Note that dequeuing an empty queue throws a RuntimeException instead of returning null.

SplPriorityQueue and heaps

SplPriorityQueue always hands out the item with the highest priority next, whatever order the items arrived in. It's ideal for task schedulers or Dijkstra-style algorithms. SplMinHeap and SplMaxHeap keep plain values ordered the same way:

PHP SplPriorityQueue and SplMinHeap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two things to remember. First, the order of items with equal priority isn't guaranteed: here the two priority-5 tickets come out in some order, but don't rely on it. If order matters, use an array priority like [5, -$sequenceNumber], because priorities are compared with the same rules as <=> and arrays compare element by element. Second, iterating a heap or priority queue consumes it, as the empty heap at the end shows.

SplObjectStorage

SplObjectStorage is a set (or map) keyed by objects. Array keys can only be integers or strings, so you can't write $seen[$user] = true. SplObjectStorage fills that gap:

PHP SplObjectStorage as an object set and map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Identity is what counts: $adaTwin has the same name but is a different object, so isset() returns false, matching how === compares objects (see Comparing, Copying and Serializing Objects). When iterating, the key is a position number and the value is the object; read its attached data with $storage[$object] or getInfo().

The example uses array syntax ($storage[$object] = ..., isset(), unset()) on purpose. Older code calls the methods attach(), contains() and detach(), which PHP 8.5 deprecated in favor of the ArrayAccess methods; on PHP 8.5 each call prints a Deprecated message.

If you only need to attach data to objects without keeping them alive (a cache of computed values, for example), PHP 8.0's WeakMap is the better choice: its entries disappear automatically when the object is no longer used anywhere else.

SplFixedArray

SplFixedArray is an array with a fixed size and integer indexes from 0. Because it doesn't need a hash table, it uses noticeably less memory than a regular array for large lists of numbers:

PHP
<?php
$scores = new SplFixedArray(3);
$scores[0] = 90;
$scores[1] = 75;
$scores[2] = 82;
echo $scores->getSize();   // 3
$scores[3] = 60;           // OutOfBoundsException: Index invalid or out of range
$scores->setSize(4);       // grow explicitly, then $scores[3] works

In everyday code, a plain array is usually fine. Reach for SplFixedArray when you hold hundreds of thousands of numeric items and memory matters.

SPL iterators worth knowing

The SPL also ships dozens of iterator classes that wrap other iterators. A few of the most useful:

  • ArrayIterator: wraps an array as an Iterator.
  • LimitIterator: a window of items (offset and count), like LIMIT ... OFFSET in SQL.
  • CallbackFilterIterator: keeps items for which a callback returns true.
  • RecursiveArrayIterator + RecursiveIteratorIterator: walk nested arrays as a flat list.
  • RecursiveDirectoryIterator: walk a folder tree (see Files and Directories).
  • CachingIterator: knows whether there is a next item, handy for "no comma after the last item" output.
PHP Combining SPL iterators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Today, many developers write these transformations as small generators instead, because a ten-line generator is often easier to read than a stack of wrapper classes. Both approaches work together: every SPL iterator is accepted wherever an iterable is expected.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order does foreach call the methods of an Iterator for the first item?

    foreach calls rewind() once, then for each item valid(), current() and key(), runs the body, and calls next().
  2. 2. Your collection stores items in a private array. What is the simplest way to make it work with foreach?

    IteratorAggregate needs one method. Returning a generator or ArrayIterator from it is all foreach needs, and each loop gets a fresh iterator.
  3. 3. What happens with count($obj) when $obj does not implement Countable?

    Since PHP 8.0, count() throws a TypeError for values that are neither arrays nor Countable objects.
  4. 4. For an ArrayAccess object, which method does $obj[] = 5; call?

    An append has no key, so PHP calls offsetSet() with a null offset. Your code decides whether to allow it.
  5. 5. You need to track which User objects have already been processed. Which structure fits best?

    Arrays only accept integer and string keys. SplObjectStorage stores objects by identity and can attach data to each one.

Summary

  • A plain object in foreach exposes its visible properties. Implement Iterator or IteratorAggregate to define iteration yourself.
  • Iterator has five methods (rewind, valid, current, key, next); IteratorAggregate has one, getIterator(), which usually returns a generator or ArrayIterator.
  • Countable makes count($obj) work; ArrayAccess maps $obj[...], isset() and unset() to four methods where you can validate.
  • ArrayAccess objects are not arrays: array functions don't accept them and nested writes like $obj['a'][] = 1 don't work.
  • SPL data structures: SplStack (LIFO), SplQueue (FIFO), SplPriorityQueue and heaps (highest or lowest first; iteration consumes them), SplObjectStorage (objects as keys), SplFixedArray (compact numeric arrays). WeakMap attaches data to objects without keeping them alive.
  • SPL iterators such as LimitIterator, CallbackFilterIterator and RecursiveIteratorIterator wrap other iterators; generators are often a simpler alternative.

Next: Attributes