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 memory usage
Consider the following PHP code that uses a generator and an array to produce numbers. What will be the output when running this code?
PHP
<?php function genNumbers() { for ($i = 0; $i < 3; $i++) { yield $i; } } $generator = genNumbers(); $array = [0, 1, 2]; echo count($generator) . "," . count($array); ?>
Attempts:
2 left
💡 Hint
Remember that generators are not arrays and do not implement Countable interface.
✗ Incorrect
In PHP, generators do not implement Countable, so calling count() on a generator causes a fatal error. Arrays can be counted normally.
🧠 Conceptual
intermediate1:30remaining
Why use generators for large data?
Why are generators more memory efficient than arrays when processing large datasets in PHP?
Attempts:
2 left
💡 Hint
Think about how generators yield values compared to arrays.
✗ Incorrect
Generators yield one value at a time, so PHP does not need to keep the whole dataset in memory, unlike arrays which store all values at once.
🔧 Debug
advanced2:30remaining
Fix the memory leak in generator usage
This PHP code uses a generator to process a large file line by line. However, memory usage grows unexpectedly. What is the cause?
PHP
<?php function readLines($file) { $handle = fopen($file, 'r'); while (($line = fgets($handle)) !== false) { yield $line; } fclose($handle); } foreach (readLines('largefile.txt') as $line) { // process line } ?>
Attempts:
2 left
💡 Hint
Check when fclose is called relative to the generator's lifecycle.
✗ Incorrect
The fclose($handle) is called after the while loop, but if the generator is not fully iterated, fclose may never run, leaving the file handle open and causing memory/resource leaks.
📝 Syntax
advanced1:30remaining
Identify the syntax error in generator function
Which option contains a syntax error in the generator function definition?
Attempts:
2 left
💡 Hint
Check if 'return yield' is valid syntax in PHP generators.
✗ Incorrect
In PHP, 'return yield' is invalid syntax. You can either yield values or return a value, but not 'return yield'.
🚀 Application
expert3:00remaining
Calculate sum using generator for memory efficiency
You want to sum numbers from 1 to 1,000,000 without loading all numbers into memory at once. Which code correctly uses a generator to do this efficiently?
Attempts:
2 left
💡 Hint
Remember that 'yield' produces values one by one, while 'return' exits the function immediately.
✗ Incorrect
Option B uses a generator with yield to produce numbers one at a time, saving memory. Option B loads all numbers into an array, using more memory. Option B returns an array, not a generator, so it loads all numbers. Option B returns immediately, so the foreach fails.