phpPHP
Module 43: PHP Iterators and GeneratorsAdvanced45 min read

Iterators & Generators (yield): Lazy Evaluation & O(1) Memory Streaming

Process millions of records in constant O(1) memory using PHP Generators (yield), Iterator, and IteratorAggregate interfaces.

Key Takeaways & Core Concepts
  • function using yield pauses execution and produces one value at a time in O(1) memory!

Iterators & Generators (yield): Lazy Evaluation & O(1) Memory Streaming

### 1. Generators (yield) vs. Arrays Returning a 1,000,000-element array consumes hundreds of MB of RAM. A Generator function using yield pauses execution and produces one value at a time in O(1) memory!

1. Lazy Range Generator with yield
1<?php
2function lazySquares(int $limit): Generator {
3 for ($i = 1; $i <= $limit; $i++) {
4 yield $i => $i * $i;
5 }
6}
7foreach (lazySquares(4) as $k => $sq) {
8 echo "$k=>$sq ";
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: Yields key-value pairs lazily one iteration at a time.
Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)