Challenge - 5 Problems
Generator Guru
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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 . ' '; } ?>
Attempts:
2 left
💡 Hint
Think about how generators yield values one by one and how arrays store all values at once.
✗ Incorrect
The generator yields values one by one, so the foreach prints '1 2 3 '. The array foreach also prints '1 2 3 '. The pipe '|' separates the outputs.
🧠 Conceptual
intermediate1:30remaining
Why use generators instead of arrays?
Which of the following is the main reason to use generators instead of arrays in PHP?
Attempts:
2 left
💡 Hint
Think about memory usage when working with large data sets.
✗ Incorrect
Generators produce values one at a time, so they use less memory than arrays which store all values at once.
🔧 Debug
advanced2: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(); ?>
Attempts:
2 left
💡 Hint
Remember what happens when a generator finishes yielding values.
✗ Incorrect
The generator yields 1 first, so current() is 1. After next(), the generator is done, so current() returns null which echoes as empty string.
❓ Predict Output
advanced2: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; ?>
Attempts:
2 left
💡 Hint
Think about how generators yield values lazily versus arrays storing all values.
✗ Incorrect
Generator uses much less memory because it yields values one by one. The array stores all 100000 values in memory, so uses more memory.
🧠 Conceptual
expert1:30remaining
When are generators most beneficial?
In which situation are generators most beneficial compared to arrays in PHP?
Attempts:
2 left
💡 Hint
Think about memory limits and data size.
✗ Incorrect
Generators allow processing large data sets without loading everything into memory, which is useful when data is too big to fit in memory.