What if you could get a final result from a generator without extra messy code?
Why Generator return values in PHP? - Purpose & Use Cases
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.
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.
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.
$results = [];
foreach ($tasks as $task) {
$results[] = process($task);
}
$summary = calculateSummary($results);function taskGenerator($tasks) {
foreach ($tasks as $task) {
yield process($task);
}
return calculateSummary();
}
$gen = taskGenerator($tasks);
foreach ($gen as $result) {
// use $result
}
$summary = $gen->getReturn();You can write clean, memory-efficient code that streams results and still captures a final return value automatically.
Processing a large file line by line, yielding each processed line, and then returning the total number of lines processed at the end.
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.