0
0
PHPprogramming~5 mins

Generator return values in PHP

Choose your learning style9 modes available
Introduction
Generators let you create lists step-by-step without using much memory. Sometimes, you want to send back a final result when the generator finishes.
When you want to process large data one piece at a time but also get a final summary.
When you need to pause and resume a function but still return a final value at the end.
When you want to save memory by generating items on demand and also return a result after all items are done.
Syntax
PHP
<?php
function exampleGenerator() {
    yield 1;
    yield 2;
    return 'done';
}

$gen = exampleGenerator();
foreach ($gen as $value) {
    echo $value . "\n";
}
$returnValue = $gen->getReturn();
echo $returnValue;
?>
The return inside a generator sets the final return value.
Use getReturn() on the generator object after iteration to get that value.
Examples
This generator yields numbers 1 to 3, then returns 'finished'.
PHP
<?php
function countToThree() {
    yield 1;
    yield 2;
    yield 3;
    return 'finished';
}

$gen = countToThree();
foreach ($gen as $num) {
    echo $num . "\n";
}
echo $gen->getReturn();
?>
Yields letters 'a' and 'b', then returns 'end'.
PHP
<?php
function letters() {
    yield 'a';
    yield 'b';
    return 'end';
}

$gen = letters();
foreach ($gen as $letter) {
    echo $letter . "\n";
}
echo $gen->getReturn();
?>
Sample Program
This program yields three fruits one by one, then after the loop, it prints the return value from the generator.
PHP
<?php
function simpleGenerator() {
    yield 'apple';
    yield 'banana';
    yield 'cherry';
    return 'all fruits yielded';
}

$gen = simpleGenerator();
foreach ($gen as $fruit) {
    echo $fruit . "\n";
}
$returnValue = $gen->getReturn();
echo $returnValue . "\n";
?>
OutputSuccess
Important Notes
You must finish iterating the generator before calling getReturn(), or it will throw an error.
The return value is different from the yielded values; it is like a final message after all yields.
Generators help save memory by not creating the whole list at once.
Summary
Generators can return a final value using return inside the function.
Use getReturn() on the generator object after iteration to get that final value.
This helps combine step-by-step data generation with a final summary or result.