Challenge - 5 Problems
Yield Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of yield from delegation with nested generators
What is the output of the following PHP code?
PHP
<?php function gen1() { yield 1; yield 2; } function gen2() { yield from gen1(); yield 3; } foreach (gen2() as $value) { echo $value . ' '; } ?>
Attempts:
2 left
💡 Hint
Remember that yield from passes all values from the delegated generator in order.
✗ Incorrect
The function gen2 uses 'yield from gen1()', which yields 1 and 2 in order, then yields 3. So the output is '1 2 3 '.
❓ Predict Output
intermediate2:00remaining
Value returned by yield from delegation
What is the output of this PHP code?
PHP
<?php function inner() { yield 1; yield 2; return 42; } function outer() { $result = yield from inner(); yield $result; } foreach (outer() as $value) { echo $value . ' '; } ?>
Attempts:
2 left
💡 Hint
The return value of the inner generator is captured by yield from and can be yielded afterwards.
✗ Incorrect
The inner generator yields 1 and 2, then returns 42. The outer generator yields from inner(), capturing 42 in $result, then yields $result. So output is '1 2 42 '.
🔧 Debug
advanced2:00remaining
Identify the error in yield from usage
What error does this PHP code produce?
PHP
<?php function gen() { yield from 123; } foreach (gen() as $v) { echo $v; } ?>
Attempts:
2 left
💡 Hint
yield from expects an iterable or generator, not a scalar value.
✗ Incorrect
The code tries to yield from an integer 123, which is not iterable. This causes a fatal error about iterating over a non-iterable.
📝 Syntax
advanced2:00remaining
Correct yield from syntax in PHP
Which option shows the correct syntax to delegate yielding to another generator in PHP?
Attempts:
2 left
💡 Hint
The keyword is two words separated by a space.
✗ Incorrect
The correct syntax uses 'yield from' with a space. Other options are invalid syntax or yield the generator object itself.
🚀 Application
expert3:00remaining
Count total yielded values using yield from delegation
Given the following PHP code, what is the value of $count after execution?
PHP
<?php function genA() { yield 1; yield 2; } function genB() { yield 3; yield 4; } function genC() { yield from genA(); yield from genB(); yield 5; } $count = 0; foreach (genC() as $v) { $count++; } echo $count; ?>
Attempts:
2 left
💡 Hint
Count all values yielded by genA, genB, and the last yield in genC.
✗ Incorrect
genA yields 2 values, genB yields 2 values, and genC yields one more value (5). Total is 2 + 2 + 1 = 5.