Challenge - 5 Problems
Yield Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP generator?
Consider the following PHP code using
yield. What will it output when run?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 the foreach loop prints each.✗ Incorrect
The generator function gen() 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
What does this PHP generator return?
What will be the output of this PHP code snippet?
PHP
<?php function gen() { yield 'a' => 1; yield 'b' => 2; } foreach (gen() as $key => $value) { echo "$key:$value "; } ?>
Attempts:
2 left
💡 Hint
Keys can be assigned in yield and are preserved in foreach.
✗ Incorrect
The generator yields keys 'a' and 'b' with values 1 and 2 respectively. The foreach loop prints each key and value pair separated by a colon and space.
❓ Predict Output
advanced2:00remaining
What is the output of this nested generator?
Analyze the following PHP code with nested generators. What will it output?
PHP
<?php function gen1() { yield 1; yield 2; } function gen2() { yield from gen1(); yield 3; } foreach (gen2() as $v) { echo $v . ' '; } ?>
Attempts:
2 left
💡 Hint
The
yield from keyword delegates yielding to another generator.✗ Incorrect
The gen2() function uses yield from gen1() to yield all values from gen1() first, then yields 3. The output is 1 2 3 .
❓ Predict Output
advanced2:00remaining
What error does this PHP code raise?
What error will this PHP code produce when executed?
PHP
<?php function gen() { yield 1; } $gen = gen(); $gen->send(10); ?>
Attempts:
2 left
💡 Hint
You must start the generator before sending a value.
✗ Incorrect
The send() method requires the generator to be started (at least one yield executed). Calling send() before starting causes a fatal error.
🧠 Conceptual
expert3:00remaining
How many values does this generator produce?
Given the following PHP generator code, how many values will be yielded when iterated?
PHP
<?php function gen() { for ($i = 0; $i < 3; $i++) { if ($i === 1) { yield $i; continue; } yield $i * 2; } } $values = iterator_to_array(gen()); echo count($values); ?>
Attempts:
2 left
💡 Hint
Count how many times
yield is called in the loop.✗ Incorrect
The loop runs 3 times (0,1,2). For i=0 and i=2, it yields i*2. For i=1, it yields i. So total yields: 3.