0
0
PHPprogramming~20 mins

Yield from delegation in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Yield Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 . ' ';
}
?>
A3 1 2
B1 3 2
C2 1 3
D1 2 3
Attempts:
2 left
💡 Hint
Remember that yield from passes all values from the delegated generator in order.
Predict Output
intermediate
2: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 . ' ';
}
?>
A1 2
B42 1 2
C1 2 42
D1 2 0
Attempts:
2 left
💡 Hint
The return value of the inner generator is captured by yield from and can be yielded afterwards.
🔧 Debug
advanced
2: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;
}
?>
ASyntax error: unexpected 'from'
BFatal error: Cannot iterate over an integer
CWarning: Undefined variable
DNo output, code runs silently
Attempts:
2 left
💡 Hint
yield from expects an iterable or generator, not a scalar value.
📝 Syntax
advanced
2:00remaining
Correct yield from syntax in PHP
Which option shows the correct syntax to delegate yielding to another generator in PHP?
Ayield from anotherGenerator();
Byield anotherGenerator();
Cyieldfrom anotherGenerator();
Dyield_from anotherGenerator();
Attempts:
2 left
💡 Hint
The keyword is two words separated by a space.
🚀 Application
expert
3: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;
?>
A5
B4
C6
D3
Attempts:
2 left
💡 Hint
Count all values yielded by genA, genB, and the last yield in genC.