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.
Practice
return statement inside a PHP generator function do?Solution
Step 1: Understand generator
In PHP,returnbehaviorreturninside a generator does not yield a value but sets a final return value.Step 2: Accessing the return value
This final value can be accessed after iteration using thegetReturn()method on the generator object.Final Answer:
It sets the final value accessible viagetReturn()after iteration. -> Option CQuick Check:
Generatorreturnsets final value = D [OK]
return in generators sets final value, not yields [OK]- Thinking
returnyields a value - Assuming
returnthrows an error - Confusing
returnwithyield
Solution
Step 1: Identify the method to get generator return
PHP providesgetReturn()method on generator objects to retrieve the final return value after iteration.Step 2: Check other options
Other methods likereturn(),yieldReturn(), orfinalValue()do not exist in PHP generators.Final Answer:
$gen->getReturn(); -> Option AQuick Check:
UsegetReturn()to get final value [OK]
getReturn() method on generator object [OK]- Using non-existent methods like
return() - Trying to get return value before iteration
- Confusing
yieldwithreturn
$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $value) {
echo $value . ' ';
}
echo $gen->getReturn();
Solution
Step 1: Iterate generator yields
The generator yields 1 and 2, so the loop prints "1 2 ".Step 2: Get the return value after iteration
After the loop,getReturn()returns 3, which is printed immediately after.Final Answer:
1 2 3 -> Option BQuick Check:
Yields + return value = 1 2 3 [OK]
getReturn() value [OK]- Expecting
returnto yield a value - Not calling
getReturn()after iteration - Assuming
getReturn()returns 0 by default
function gen() {
yield 1;
return 2;
yield 3;
}
$g = gen();
foreach ($g as $v) {
echo $v . ' ';
}
echo $g->getReturn();
Solution
Step 1: Analyze code flow after
Oncereturnreturn 2;executes, the function ends, soyield 3;is never reached.Step 2: Confirm other statements
Usingreturnin generators is valid,getReturn()exists, and no minimum yield count is required.Final Answer:
Theyield 3;afterreturnis unreachable code. -> Option AQuick Check:
Code afterreturnis unreachable = B [OK]
return in generator is never executed [OK]- Thinking
yieldafterreturnruns - Believing
returnis not allowed in generators - Ignoring unreachable code warnings
Solution
Step 1: Check yielding numbers 1 to 3
function gen() { $sum = 0; for ($i = 1; $i <= 3; $i++) { $sum += $i; yield $i; } return $sum; } uses a loop to yield 1, 2, 3 and sums them in$sum.Step 2: Verify other options
The second option yields 1-3 but returns$i(4 after loop), not sum 6. The third has unreachableyield 7;after return. The fourth returns 7, wrong sum.Final Answer:
The code that accumulates the sum during yielding -> Option DQuick Check:
Yield loop + sum return = A [OK]
- Placing code after
return(unreachable) - Returning wrong sum value
- Not accumulating sum during yield
Ready to prove it?
Pass the test and this pattern moves unknown
