Bird
Raised Fist0
PHPprogramming~5 mins

Memory efficiency with generators in PHP

Choose your learning style10 modes available
Introduction

Generators help save memory by producing values one at a time instead of all at once.

When working with large lists or files that don't fit in memory.
When you want to process data step-by-step without loading everything.
When you want to improve performance by avoiding big memory use.
When reading large logs or streams line by line.
When you want to create simple iterators without extra memory cost.
Syntax
PHP
<?php
function generatorName() {
    yield 'value1';
    yield 'value2';
    // more yields
}

foreach (generatorName() as $item) {
    // use $item
}
?>

yield pauses the function and returns a value each time.

Generators do not store all values in memory at once.

Examples
This generator yields numbers 1 to 3 one by one.
PHP
<?php
function countToThree() {
    yield 1;
    yield 2;
    yield 3;
}

foreach (countToThree() as $number) {
    echo $number . "\n";
}
This generator yields numbers from 5 to 7 using a loop.
PHP
<?php
function rangeGenerator($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

foreach (rangeGenerator(5, 7) as $num) {
    echo $num . "\n";
}
Sample Program

This program uses a generator to print numbers from 1 to 5 without storing them all at once.

PHP
<?php
function bigRange($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

foreach (bigRange(1, 5) as $value) {
    echo "Value: $value\n";
}
OutputSuccess
Important Notes

Generators are great for saving memory with big data.

Each yield returns one value and pauses the function.

You can loop over generators just like arrays.

Summary

Generators produce values one at a time to save memory.

Use yield inside functions to create generators.

Generators help handle large data efficiently.

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