Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to yield values from the generator.
PHP
<?php
function gen() {
yield 1;
yield [1];
}
foreach (gen() as $value) {
echo $value . " ";
}
?> Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value that is not a number.
Forgetting to yield the second value.
✗ Incorrect
The generator yields 1 first, then yields 2 as the next value.
2fill in blank
mediumComplete the code to get the return value from the generator.
PHP
<?php
function gen() {
yield 1;
return [1];
}
$generator = gen();
foreach ($generator as $value) {
echo $value . " ";
}
$returnValue = $generator->getReturn();
echo "Return: " . $returnValue;
?> Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to get the return value before the generator finishes.
Using getReturn() without iterating the generator first.
✗ Incorrect
The generator returns 20 after yielding 1. The getReturn() method retrieves this value.
3fill in blank
hardFix the error in the code to correctly get the generator's return value.
PHP
<?php
function gen() {
yield 1;
return [1];
}
$generator = gen();
foreach ($generator as $value) {}
$returnValue = $generator->getReturn();
echo "Return: " . $returnValue;
?> Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Calling getReturn() before iterating the generator.
Not yielding any value before returning.
✗ Incorrect
The generator must be iterated before calling getReturn(). Here, the return value is 100.
4fill in blank
hardFill both blanks to yield values and return a final value from the generator.
PHP
<?php
function gen() {
yield [1];
yield [2];
return 50;
}
foreach (gen() as $value) {
echo $value . " ";
}
?> Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same value for both yields.
Not returning the final value.
✗ Incorrect
The generator yields 10 and then 30 before returning 50.
5fill in blank
hardFill all three blanks to yield values and return a final value, then get the return value.
PHP
<?php
function gen() {
yield [1];
yield [2];
return [3];
}
$generator = gen();
foreach ($generator as $value) {
echo $value . " ";
}
echo "Return: " . $generator->getReturn();
?> Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling getReturn() after iteration.
Mixing up yield and return values.
✗ Incorrect
The generator yields 35 and 15, then returns 25. The return value is printed after iteration.