0
0
PHPprogramming~3 mins

Why Generator return values in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could get a final result from a generator without extra messy code?

The Scenario

Imagine you have a long list of tasks to process one by one, and you want to know when all tasks are done and get a final summary. Doing this manually means running through the entire list, keeping track of progress, and then separately calculating the summary after finishing.

The Problem

This manual way is slow and clunky. You have to write extra code to track when the loop ends and to collect the final result. It's easy to forget to do this, causing bugs or messy code that's hard to read and maintain.

The Solution

Generator return values let you yield each task result as you go, and then return a final value when done. This means you can process items one by one efficiently, and still get a neat summary at the end without extra tracking code.

Before vs After
Before
$results = [];
foreach ($tasks as $task) {
    $results[] = process($task);
}
$summary = calculateSummary($results);
After
function taskGenerator($tasks) {
    foreach ($tasks as $task) {
        yield process($task);
    }
    return calculateSummary();
}
$gen = taskGenerator($tasks);
foreach ($gen as $result) {
    // use $result
}
$summary = $gen->getReturn();
What It Enables

You can write clean, memory-efficient code that streams results and still captures a final return value automatically.

Real Life Example

Processing a large file line by line, yielding each processed line, and then returning the total number of lines processed at the end.

Key Takeaways

Manual tracking of final results is slow and error-prone.

Generator return values combine streaming data with a final return.

This leads to cleaner, more efficient, and easier-to-read code.