Bird
Raised Fist0
PHPprogramming~20 mins

Memory efficiency with generators in PHP - Practice Problems & Coding Challenges

Choose your learning style10 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 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);
?>
A0,3
B3,3
C1,3
DFatal error: Uncaught Error: count(): Parameter must be an array or an object that implements Countable
Attempts:
2 left
💡 Hint
Remember that generators are not arrays and do not implement Countable interface.
🧠 Conceptual
intermediate
1:30remaining
Why use generators for large data?
Why are generators more memory efficient than arrays when processing large datasets in PHP?
AGenerators load all data into memory at once, making processing faster.
BGenerators automatically compress data to save memory.
CGenerators produce values one at a time, so they don't store the entire dataset in memory.
DGenerators store data on disk instead of memory.
Attempts:
2 left
💡 Hint
Think about how generators yield values compared to arrays.
🔧 Debug
advanced
2: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
}
?>
AThe generator does not close the file handle after iteration ends, causing a resource leak.
BThe file handle is closed too early inside the generator.
CUsing yield inside a while loop causes memory to accumulate.
DThe fgets function reads the entire file into memory.
Attempts:
2 left
💡 Hint
Check when fclose is called relative to the generator's lifecycle.
📝 Syntax
advanced
1:30remaining
Identify the syntax error in generator function
Which option contains a syntax error in the generator function definition?
Afunction gen() { return yield 1; }
Bfunction gen() { yield from [1, 2, 3]; }
Cfunction gen() { yield 1; yield 2; }
Dfunction gen() { yield; }
Attempts:
2 left
💡 Hint
Check if 'return yield' is valid syntax in PHP generators.
🚀 Application
expert
3: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?
A
&lt;?php
$numbers = range(1, 1000000);
$sum = array_sum($numbers);
echo $sum;
?&gt;
B
&lt;?php
function numbers() {
    for ($i = 1; $i &lt;= 1000000; $i++) {
        yield $i;
    }
}
$sum = 0;
foreach (numbers() as $num) {
    $sum += $num;
}
echo $sum;
?&gt;
C
&lt;?php
function numbers() {
    return range(1, 1000000);
}
$sum = 0;
foreach (numbers() as $num) {
    $sum += $num;
}
echo $sum;
?&gt;
D
&lt;?php
function numbers() {
    for ($i = 1; $i &lt;= 1000000; $i++) {
        return $i;
    }
}
$sum = 0;
foreach (numbers() as $num) {
    $sum += $num;
}
echo $sum;
?&gt;
Attempts:
2 left
💡 Hint
Remember that 'yield' produces values one by one, while 'return' exits the function immediately.

Practice

(1/5)
1. What is the main advantage of using a generator in PHP compared to returning an array?
easy
A. It automatically caches all values for quick access.
B. It uses less memory by producing values one at a time.
C. It runs faster because it compiles code differently.
D. It allows multiple return statements in a function.

Solution

  1. Step 1: Understand how generators produce values

    Generators use yield to produce one value at a time instead of creating the whole list in memory.
  2. Step 2: Compare memory usage with arrays

    Returning an array stores all values at once, using more memory. Generators save memory by generating values on demand.
  3. Final Answer:

    It uses less memory by producing values one at a time. -> Option B
  4. Quick Check:

    Generators save memory = C [OK]
Hint: Generators yield values one by one, saving memory [OK]
Common Mistakes:
  • Thinking generators cache all values like arrays
  • Confusing speed with memory usage
  • Believing generators return all values at once
2. Which of the following is the correct syntax to create a generator function in PHP?
easy
A. function gen() { yield 1; yield 2; yield 3; }
B. function gen() { return [1, 2, 3]; }
C. function gen() { echo 1; echo 2; echo 3; }
D. function gen() { print(1, 2, 3); }

Solution

  1. Step 1: Identify generator syntax

    Generators use the yield keyword inside functions to produce values one at a time.
  2. Step 2: Check each option

    function gen() { yield 1; yield 2; yield 3; } uses yield correctly. Others either return arrays or print values, not generators.
  3. Final Answer:

    function gen() { yield 1; yield 2; yield 3; } -> Option A
  4. Quick Check:

    Generators use yield = B [OK]
Hint: Look for the yield keyword inside the function [OK]
Common Mistakes:
  • Using return instead of yield for generators
  • Confusing echo/print with yield
  • Missing yield keyword in generator functions
3. What will be the output of the following PHP code?
function gen() {
  for ($i = 1; $i <= 3; $i++) {
    yield $i * 2;
  }
}
foreach (gen() as $value) {
  echo $value . ' ';
}
medium
A. 2 4 6
B. 1 2 3
C. 0 2 4
D. Error: yield cannot be used in loops

Solution

  1. Step 1: Analyze the generator loop

    The loop runs from 1 to 3, yielding $i * 2 each time: 2, 4, 6.
  2. Step 2: Understand foreach output

    Each yielded value is printed with a space, so output is "2 4 6 ".
  3. Final Answer:

    2 4 6 -> Option A
  4. Quick Check:

    Yielded values doubled = A [OK]
Hint: Multiply loop index by 2 and yield each value [OK]
Common Mistakes:
  • Assuming yield can't be used in loops
  • Printing loop index instead of multiplied value
  • Confusing yield with return inside loops
4. Identify the error in this generator function:
function gen() {
  yield 1;
  return 2;
  yield 3;
}
medium
A. Generators must yield only one value.
B. The function cannot have a return statement after yield.
C. The yield after return will never execute.
D. The function must use echo instead of yield.

Solution

  1. Step 1: Understand return behavior in generators

    When a return statement is reached, the generator stops and no further yields run.
  2. Step 2: Analyze the code flow

    After yielding 1, the function returns 2, so yield 3 is never executed.
  3. Final Answer:

    The yield after return will never execute. -> Option C
  4. Quick Check:

    Return stops generator = A [OK]
Hint: Return ends generator; yields after return are skipped [OK]
Common Mistakes:
  • Thinking return after yield is invalid syntax
  • Expecting all yields to run after return
  • Confusing echo with yield in generators
5. You want to process a large file line by line without loading it all into memory. Which approach using generators is best?
hard
A. Read the entire file into an array, then yield each line.
B. Read and yield lines only after closing the file.
C. Use a generator that yields the whole file content as a single string.
D. Use a generator function that opens the file and yields one line at a time.

Solution

  1. Step 1: Understand memory usage for large files

    Loading the entire file into memory (Read the entire file into an array, then yield each line.) uses a lot of memory, which is inefficient.
  2. Step 2: Use generator to yield lines one by one

    Opening the file and yielding each line as it is read (Use a generator function that opens the file and yields one line at a time.) saves memory by processing lines lazily.
  3. Step 3: Evaluate other options

    Use a generator that yields the whole file content as a single string. yields the whole file at once, no memory saving. Read and yield lines only after closing the file. yields after closing file, which is invalid.
  4. Final Answer:

    Use a generator function that opens the file and yields one line at a time. -> Option D
  5. Quick Check:

    Yield lines lazily for memory efficiency = D [OK]
Hint: Yield lines while reading file, don't load all at once [OK]
Common Mistakes:
  • Loading entire file before yielding
  • Yielding whole file content as one string
  • Trying to yield after file is closed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard