0
0
PHPprogramming~10 mins

Generator return values in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A2
B3
C4
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using a value that is not a number.
Forgetting to yield the second value.
2fill in blank
medium

Complete 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'
A10
B30
C20
D40
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to get the return value before the generator finishes.
Using getReturn() without iterating the generator first.
3fill in blank
hard

Fix 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'
A100
B200
C300
D400
Attempts:
3 left
💡 Hint
Common Mistakes
Calling getReturn() before iterating the generator.
Not yielding any value before returning.
4fill in blank
hard

Fill 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'
A10
B20
C30
D40
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same value for both yields.
Not returning the final value.
5fill in blank
hard

Fill 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'
A5
B15
C25
D35
Attempts:
3 left
💡 Hint
Common Mistakes
Not calling getReturn() after iteration.
Mixing up yield and return values.