PHP 8: Modern PHP Development · Modern PHP Syntax & Types

Generators and Iterables

Process large data sets lazily with yield, keys and generator delegation.

A generator is a function containing yield; calling it returns a Generator object that produces values lazily, one at a time. Generators let you stream large files or database results with constant memory, build pipelines, and implement iterators without writing an Iterator class. Use yield from to delegate to another generator or array, and the iterable type to accept arrays or Traversables.

<?php
/** @return Generator<int, array<string, string>> */
function readCsv(string $path): Generator
{
    $handle = fopen($path, 'rb') ?: throw new RuntimeException("Cannot open {$path}");
    try {
        $headers = fgetcsv($handle);
        while (($row = fgetcsv($handle)) !== false) {
            yield array_combine($headers, $row);
        }
    } finally {
        fclose($handle);
    }
}

foreach (readCsv('orders.csv') as $line => $order) {
    // only one row in memory at a time
}

Common pitfalls

  • Generators can only be iterated once; calling foreach again on the same generator throws.
  • Calling iterator_to_array() on a huge generator defeats the memory benefit.
  • Forgetting that generator code doesn't run until iteration starts — errors appear later than expected.

Key points

  • Generators stream data with constant memory
  • yield from delegates to inner iterables
  • Use finally to release resources

Further reading: PHP manual: generators

Practice questions

Why use a generator to read a 2 GB CSV file?

Answer

A generator yields one row at a time, so memory stays roughly constant instead of loading the whole file into an array. Processing can start immediately and stop early.

When does the code inside a generator function start running?

Answer

Only when iteration begins (e.g., the first foreach step or ->current()). Calling the function just creates the Generator object.

Open in the app to mark lessons complete, take notes and track your progress.