What is yield in PHP & how it is different from return?

Many times we process the data and creates an array. That array later on will be processed further. In this scenario we need to create an array which occupy the memory usage. Is there any way by which we can avoid to create an array and still we can process on that data one by one? The answer is Yes, Yield is for that purpose.

The yield keyword returns a value and pauses the function, saving its state.

The next time the generator is called (e.g., via foreach or current()), the function resumes from where it left off and continues executing until it hits another yield or finishes.

function generateEvenNumbers($max) {
    for ($i = 0; $i <= $max; $i += 2) {
        yield $i;
    }
}

foreach (generateEvenNumbers(10) as $evenNumber) {
    echo $evenNumber . "\n";
}

//Outupt
0
2
4
6
8
10

yield vs return:

  • yield allows you to return multiple values one at a time and maintain the function’s state.
  • return is used to return a single value and exit the function immediately.

This is particularly useful when dealing with large datasets or when you want to improve performance by reducing memory usage.