Challenge - 5 Problems
Generator Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple generator with yield
What is the output of this PHP code when executed?
PHP
<?php function gen() { yield 1; yield 2; yield 3; } foreach (gen() as $value) { echo $value . ' '; } ?>
Attempts:
2 left
💡 Hint
Remember that yield produces values one by one and foreach iterates over them.
✗ Incorrect
The generator yields values 1, 2, and 3 sequentially. The foreach loop prints each value followed by a space, resulting in '1 2 3 '.
❓ Predict Output
intermediate2:00remaining
Generator state after partial iteration
What will be the output of this PHP code?
PHP
<?php function gen() { yield 'a'; yield 'b'; yield 'c'; } $g = gen(); echo $g->current(); $g->next(); echo $g->current(); ?>
Attempts:
2 left
💡 Hint
The generator starts at the first yield value before calling next().
✗ Incorrect
When the generator is created, current() returns the first yielded value 'a'. After calling next(), current() returns the second yielded value 'b'. So the output is 'ab'.
🔧 Debug
advanced2:00remaining
Identify the error in generator usage
What error does this PHP code produce when run?
PHP
<?php function gen() { yield 1; yield 2; } $g = gen(); $g->next(); $g->next(); $g->next(); echo $g->current(); ?>
Attempts:
2 left
💡 Hint
What happens when you call next() past the last yield?
✗ Incorrect
After the generator yields 1 and 2, the third next() call moves the generator past the end. current() then returns NULL because the generator is finished.
🧠 Conceptual
advanced2:00remaining
Behavior of yield in generator with return
What is the output of this PHP code?
PHP
<?php function gen() { yield 10; return 20; } $g = gen(); foreach ($g as $value) { echo $value . ' '; } echo $g->getReturn(); ?>
Attempts:
2 left
💡 Hint
The return value of a generator can be retrieved after iteration.
✗ Incorrect
The generator yields 10, which is printed with a space. After iteration, getReturn() returns the value 20 from the return statement, which is then printed.
❓ Predict Output
expert2:00remaining
Generator with keys and values
What is the output of this PHP code?
PHP
<?php function gen() { yield 'x' => 100; yield 'y' => 200; } foreach (gen() as $key => $value) { echo "$key:$value "; } ?>
Attempts:
2 left
💡 Hint
Yield can specify keys for the generated values.
✗ Incorrect
The generator yields keys 'x' and 'y' with values 100 and 200 respectively. The foreach loop prints each key and value separated by a colon and space.