0
0
PHPprogramming~20 mins

Why generators are needed in PHP - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Generator Guru
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of generator vs array in PHP
What will be the output of this PHP code that uses a generator compared to an array?
PHP
<?php
function genNumbers() {
    for ($i = 1; $i <= 3; $i++) {
        yield $i;
    }
}

$generator = genNumbers();
$array = [1, 2, 3];

foreach ($generator as $num) {
    echo $num . ' ';
}
echo "|";
foreach ($array as $num) {
    echo $num . ' ';
}
?>
AArray to string conversion error
B123|123
C1 2 3 |
D1 2 3 |1 2 3
Attempts:
2 left
💡 Hint
Think about how generators yield values one by one and how arrays store all values at once.
🧠 Conceptual
intermediate
1:30remaining
Why use generators instead of arrays?
Which of the following is the main reason to use generators instead of arrays in PHP?
AGenerators use less memory by producing values one at a time.
BGenerators automatically sort the data for you.
CGenerators can only be used with numbers.
DGenerators store all values in memory for faster access.
Attempts:
2 left
💡 Hint
Think about memory usage when working with large data sets.
🔧 Debug
advanced
2:00remaining
Identify the error in generator usage
What error will this PHP code produce?
PHP
<?php
function gen() {
    yield 1;
    return 2;
}
$g = gen();
$g->next();
echo $g->current();
$g->next();
echo $g->current();
?>
ANotice: Undefined property
BFatal error: Cannot access current() after generator is done
COutputs '1' then empty string
DOutputs '12'
Attempts:
2 left
💡 Hint
Remember what happens when a generator finishes yielding values.
Predict Output
advanced
2:30remaining
Memory usage difference between generator and array
What will be the output of this PHP code that compares memory usage of generator and array?
PHP
<?php
function genLarge() {
    for ($i = 0; $i < 100000; $i++) {
        yield $i;
    }
}

$startMem = memory_get_usage();
foreach (genLarge() as $v) {}
$genMem = memory_get_usage() - $startMem;

$startMem = memory_get_usage();
$array = range(0, 99999);
$arrayMem = memory_get_usage() - $startMem;

echo $genMem . '|' . $arrayMem;
?>
ALarge number|Small number
BSmall number|Large number
C0|0
DSame number|Same number
Attempts:
2 left
💡 Hint
Think about how generators yield values lazily versus arrays storing all values.
🧠 Conceptual
expert
1:30remaining
When are generators most beneficial?
In which situation are generators most beneficial compared to arrays in PHP?
AWhen processing very large data sets that don't fit in memory.
BWhen you want to store all data permanently in memory.
CWhen you want to sort data quickly.
DWhen you need to access elements randomly by index.
Attempts:
2 left
💡 Hint
Think about memory limits and data size.