0
0
PHPprogramming~20 mins

Yield keyword behavior in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Yield Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 . ' ';
}
?>
AError: yield used outside function
B123
C1 2 3
DArray
Attempts:
2 left
💡 Hint
Remember that yield produces values one by one, and the foreach loop prints each.
Predict Output
intermediate
2: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 ";
}
?>
Aa:1 b:2
B1:a 2:b
Ca b
DError: Invalid key in yield
Attempts:
2 left
💡 Hint
Keys can be assigned in yield and are preserved in foreach.
Predict Output
advanced
2: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 . ' ';
}
?>
AError: yield from not supported
B3 1 2
C1 3 2
D1 2 3
Attempts:
2 left
💡 Hint
The yield from keyword delegates yielding to another generator.
Predict Output
advanced
2: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);
?>
ANo error, outputs 10
BFatal error: Cannot send() to a generator that has not started
C1
D10
Attempts:
2 left
💡 Hint
You must start the generator before sending a value.
🧠 Conceptual
expert
3: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);
?>
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
Count how many times yield is called in the loop.