📖 Scenario: Imagine you have a large list of numbers and you want to process them one by one without using too much memory. Using generators in PHP helps you do this efficiently.
🎯 Goal: You will create a generator function to yield numbers from 1 to 1000000, then use it to sum these numbers without loading all of them into memory at once.
📋 What You'll Learn
Create a generator function called numberGenerator that yields numbers from 1 to 1000000
Create a variable called total and set it to 0
Use a foreach loop with variable $number to iterate over numberGenerator() and add each number to total
Print the value of total
💡 Why This Matters
🌍 Real World
Generators are useful when working with large data sets like logs, big files, or streams where loading everything at once is not possible.
💼 Career
Understanding generators helps you write efficient code in PHP, which is valuable for backend development and handling large-scale applications.
Progress0 / 4 steps
1
Create the generator function
Create a generator function called numberGenerator that yields numbers from 1 to 1000000 using a for loop.
PHP
Hint
Use yield inside the for loop to return one number at a time.
2
Create the total variable
Create a variable called total and set it to 0.
PHP
Hint
Just write $total = 0; to start counting from zero.
3
Sum numbers using the generator
Use a foreach loop with variable $number to iterate over numberGenerator() and add each number to total.
PHP
Hint
Use foreach (numberGenerator() as $number) and inside add $number to $total.
4
Print the total sum
Write print($total); to display the sum of numbers from 1 to 1000000.
PHP
Hint
The sum of numbers from 1 to 1000000 is 500000500000. Use print($total); to show it.
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
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.
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.
Final Answer:
It uses less memory by producing values one at a time. -> Option B
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
Step 1: Identify generator syntax
Generators use the yield keyword inside functions to produce values one at a time.
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.
Final Answer:
function gen() { yield 1; yield 2; yield 3; } -> Option A
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
Step 1: Analyze the generator loop
The loop runs from 1 to 3, yielding $i * 2 each time: 2, 4, 6.
Step 2: Understand foreach output
Each yielded value is printed with a space, so output is "2 4 6 ".
Final Answer:
2 4 6 -> Option A
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
Step 1: Understand return behavior in generators
When a return statement is reached, the generator stops and no further yields run.
Step 2: Analyze the code flow
After yielding 1, the function returns 2, so yield 3 is never executed.
Final Answer:
The yield after return will never execute. -> Option C
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
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.
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.
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.
Final Answer:
Use a generator function that opens the file and yields one line at a time. -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.