SPL Iterators

SPL Iterators and Iterator Pipelines

SPL also ships two dozen iterator classes. A few are sources (ArrayIterator, DirectoryIterator); most wrap another iterator: CallbackFilterIterator drops items, LimitIterator pages, RegexIterator matches keys or values, and RecursiveIteratorIterator flattens a tree such as the shop's categories or a directory (Files, Directories and Streams). Stacked, they form a pipeline that pulls each item through every stage before reading the next.

Walking the category tree and paging through in-stock productsPHP
<?php
$tree = ['Books' => ['Programming' => [], 'Databases' => [], 'Design' => []],
         'Accessories' => []];
$walk = new RecursiveIteratorIterator(new RecursiveArrayIterator($tree),
  RecursiveIteratorIterator::SELF_FIRST);
foreach ($walk as $name => $children) echo str_repeat('  ', $walk->getDepth()), $name, "\n";
$stock = ['BK-PHP-01' => 25, 'BK-SQL-01' => 12, 'BK-SQL-02' => 0, 'BK-LAR-01' => 18,
          'BK-UX-01' => 7, 'AC-MUG-01' => 60];
$books = new RegexIterator(new ArrayIterator($stock), '/^BK-/', RegexIterator::MATCH,
  RegexIterator::USE_KEY);
$inStock = new CallbackFilterIterator($books, fn(int $qty) => $qty > 0);
$page2 = new LimitIterator($inStock, 2, 2);                 // offset 2, count 2
echo json_encode(iterator_to_array($page2)), ' of ', iterator_count($inStock), "\n";
Output
Books
  Programming
  Databases
  Design
Accessories
{"BK-LAR-01":18,"BK-UX-01":7} of 4

No intermediate arrays are built. For data already in an array, array_filter() and array_slice() (Arrays and the Array Library) are simpler; iterators pay off on large or lazy sources such as files and database cursors.