Recall & Review
beginner
What is a generator in PHP?
A generator is a special function that can pause and resume its execution, yielding values one at a time instead of returning them all at once. This helps save memory.
Click to reveal answer
beginner
How does a generator improve memory efficiency compared to returning an array?
Generators produce values one by one on demand, so PHP does not need to store the entire list in memory at once, unlike arrays which hold all values simultaneously.
Click to reveal answer
beginner
Which keyword is used in PHP to yield values from a generator?
The
yield keyword is used inside a generator function to return a value and pause execution until the next value is requested.Click to reveal answer
beginner
Can generators be iterated with foreach loops in PHP?
Yes, generators implement the Iterator interface, so you can use
foreach to loop through values yielded by a generator just like an array.Click to reveal answer
beginner
Give a simple example of a PHP generator function that yields numbers from 1 to 3.
<?php
function numbers() {
yield 1;
yield 2;
yield 3;
}
foreach (numbers() as $num) {
echo $num . " ";
}
// Output: 1 2 3
?>Click to reveal answer
What does the
yield keyword do in a PHP generator?✗ Incorrect
yield returns a value and pauses the generator, allowing it to resume later.
Why are generators more memory efficient than arrays?
✗ Incorrect
Generators produce values one by one, so they don't keep all values in memory at once.
Which PHP construct can you use to loop through a generator's values?
✗ Incorrect
Generators implement Iterator, so foreach works directly.
What happens if you call a generator function in PHP?
✗ Incorrect
Calling a generator function returns a Generator object; the code runs when iterated.
Which of these is NOT a benefit of using generators?
✗ Incorrect
Generators do not provide faster access to all elements at once; they produce values one at a time.
Explain how generators help save memory when processing large data in PHP.
Think about how you can get one item at a time instead of all items together.
You got /4 concepts.
Describe how you would use a generator in PHP to loop through a sequence of numbers.
Remember the special keyword that returns values step-by-step.
You got /4 concepts.