Generators allow you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, preventing out-of-memory errors on massive datasets.
PHP Generators and Yield
Generate large sequences on the fly with minimal memory footprint.
Key Takeaways: PHP Generators and Yield
Mastering PHP Generators and Yield helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
PHP Generators and Yield Code Example
PHPfunction getFibonacci($limit) {
$a = 0; $b = 1;
for ($i = 0; $i < $limit; $i++) {
yield $a;
[$a, $b] = [$b, $a + $b];
}
}
foreach (getFibonacci(6) as $num) {
echo $num . " ";
}
Output
0 1 1 2 3 5
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services