Sobes.tech
Junior — Middle

Explain what a generator in PHP is and how it works.

sobes.tech AI

Answer from AI

A generator in PHP is a special type of iterator that allows creating a sequence of values one at a time without storing the entire sequence in memory. Generators are implemented using the yield keyword inside a function.

When a generator function is called, it returns a generator object that can be iterated over. Each time the iteration proceeds, the function resumes execution from the last yield, returning a new value.

This is convenient for working with large datasets or infinite sequences, as it saves memory and simplifies the code.

Example of a generator in PHP:

function numbers() {
    for ($i = 0; $i < 5; $i++) {
        yield $i;
    }
}

foreach (numbers() as $num) {
    echo $num . "\n";
}

This code will output numbers from 0 to 4, generating them one by one at each iteration.