0
0
PHPprogramming~5 mins

Memory efficiency with generators in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ACreates a new array
BReturns a value and pauses the function execution
CEnds the function and returns all values at once
DThrows an error
Why are generators more memory efficient than arrays?
AThey produce values one at a time on demand
BThey store all values in memory
CThey use less CPU but more memory
DThey convert values to strings
Which PHP construct can you use to loop through a generator's values?
Aforeach
Bwhile with array_pop
Cfor with count()
Ddo-while with array_shift
What happens if you call a generator function in PHP?
AIt throws a syntax error
BIt immediately runs all code and returns an array
CIt returns a Generator object without running the code
DIt returns null
Which of these is NOT a benefit of using generators?
ASimpler code for producing sequences
BAbility to pause and resume function execution
CLower memory usage for large data sets
DFaster access to all elements at once
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.