Glossary

Generators (yield)

A generator is a function that returns values one at a time using yield, without loading the entire result into memory. Ideal for processing large datasets: CSV files, DB results, infinite sequences.

Example

function csvReader(string $file): Generator {
  $fh = fopen($file, 'r');
  while (!feof($fh)) {
    yield fgetcsv($fh);
  }
  fclose($fh);
}

foreach (csvReader('million_rows.csv') as $row) {
  process($row); // only one row in memory
}

Advantages over arrays

An array of millions of rows takes hundreds of MB. A generator uses O(1) memory regardless of size. Execution is lazy: the next value is computed only when requested.

yield from

yield from delegates execution to another generator or iterable — useful for composing generators.