Sobes.tech
Middle

How does a generator work in PHP?

sobes.tech AI

Answer from AI

Generator — is a function that returns an iterator. It allows iterating over a dataset without loading the entire array into memory, using the yield keyword. Each time yield is called, the function execution is paused, a value is returned, and the function's state is preserved. When next() is called on the iterator, execution continues from the last pause.

<?php

function numberGenerator($limit) {
    for ($i = 1; $i <= $limit; $i++) {
        yield $i; // Pauses execution and returns a value
    }
}

$numbers = numberGenerator(5);

foreach ($numbers as $number) {
    echo $number . " "; // Outputs: 1 2 3 4 5
}

?>

Advantages:

  • Memory efficiency: Allows processing large data volumes without loading them entirely into memory.
  • Lazy loading: Values are generated on demand when needed.
  • Improved performance for certain tasks, such as reading large files.

Used for iterating over large collections, reading files line by line, implementing infinite sequences.

How does a generator work in PHP? — PHP - sobes.tech