Bird
Raised Fist0
PHPprogramming~10 mins

Memory efficiency with generators in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Memory efficiency with generators
Start generator function
↓
Yield one value
↓
Pause function, keep state
↓
Request next value?
No→End generator
Yes↓
Resume function from pause
↓
Yield next value
↓
Repeat until done
The generator function yields one value at a time, pauses, and resumes on demand, saving memory by not storing all values at once.
Execution Sample
PHP
<?php
function countToThree() {
  yield 1;
  yield 2;
  yield 3;
}
foreach (countToThree() as $num) {
  echo $num . " ";
}
This code yields numbers 1 to 3 one by one, printing each without storing all at once.
Execution Table
StepGenerator StateYielded ValueActionOutput
1Start functionNoneYield 11
2Paused after yield 11Resume and yield 22
3Paused after yield 22Resume and yield 33
4Paused after yield 33Resume and end function
5Function endedNoneStop iteration
💡 Generator ends after yielding 3, no more values to yield.
Variable Tracker
VariableStartAfter 1After 2After 3Final
Generator StateNot startedPaused after yield 1Paused after yield 2Paused after yield 3Ended
Yielded ValueNone123None
Key Moments - 3 Insights
Why doesn't the generator store all values at once?
Because it yields one value and pauses (see execution_table steps 1-3), it only keeps current state, saving memory.
What happens when the generator finishes yielding all values?
It ends the function and stops iteration (see execution_table step 5), so no more values are produced.
How does the foreach loop get each value from the generator?
Each loop iteration resumes the generator from pause, gets the next yielded value, then pauses again (see execution_table steps 2-4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the generator state after step 2?
APaused after yield 2
BFunction ended
CPaused after yield 1
DNot started
💡 Hint
Check the 'Generator State' column in execution_table row for step 2.
At which step does the generator stop yielding values?
AStep 3
BStep 5
CStep 4
DStep 2
💡 Hint
Look at the 'Action' column where it says 'Stop iteration' in execution_table.
If the generator yielded 5 values instead of 3, how would the variable 'Yielded Value' change in variable_tracker?
AIt would have values up to 5 before final None
BIt would stay the same with only 3 values
CIt would end earlier
DIt would never yield any value
💡 Hint
Check how 'Yielded Value' changes after each yield in variable_tracker.
Concept Snapshot
PHP generators yield values one at a time.
They pause after each yield, saving memory.
foreach resumes generator to get next value.
No full list stored in memory.
Useful for large data or streams.
Full Transcript
This example shows how PHP generators work to save memory. The function countToThree yields numbers 1, 2, and 3 one by one. Each yield pauses the function, keeping its state. The foreach loop resumes the generator to get the next value. This way, the program never stores all values at once, making it memory efficient. The execution table traces each step: starting the function, yielding values, pausing, resuming, and finally ending. The variable tracker shows how the generator state and yielded values change over time. Key moments clarify why generators save memory and how iteration stops. The quiz tests understanding of generator states and output. Overall, generators help handle data step-by-step without heavy memory use.

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