0
0
PHPprogramming~20 mins

Generator function execution model in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generator Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 . ' ';
}
?>
A1 2 3
B123
CArray
DError: Cannot use foreach on generator
Attempts:
2 left
💡 Hint
Remember that yield produces values one by one and foreach iterates over them.
Predict Output
intermediate
2: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();
?>
AError: Cannot call current() before next()
Bbc
Cab
Da
Attempts:
2 left
💡 Hint
The generator starts at the first yield value before calling next().
🔧 Debug
advanced
2: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();
?>
AFatal error: Call to undefined method
BNULL
CNotice: Undefined offset
DError: Cannot advance generator beyond end
Attempts:
2 left
💡 Hint
What happens when you call next() past the last yield?
🧠 Conceptual
advanced
2: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();
?>
AError: getReturn() not supported
B10
C20
D10 20
Attempts:
2 left
💡 Hint
The return value of a generator can be retrieved after iteration.
Predict Output
expert
2: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 ";
}
?>
Ax:100 y:200
B100:x 200:y
C0:100 1:200
DError: Invalid key syntax
Attempts:
2 left
💡 Hint
Yield can specify keys for the generated values.