Limited Offer
60% OFF on all plans!

Iterators & Generators in PHP

Deep dive into iterators and generators in PHP: the Iterator interface, custom iterables, generator functions, yield, lazy evaluation, infinite sequences, send/return, and real-world use cases.

Why Iterators & Generators Matter

Iterators and generators give you low-level control over how data is produced and consumed. Instead of loading an entire dataset into memory, you produce values one at a time — enabling memory-efficient processing of large or infinite sequences.

1. Pull-Based Data Flow

Consumer pulls values on demand.

The Iterator Interface

PHP's built-in `Iterator` interface defines five methods that make any object usable in a `foreach` loop.

1. Iterator Interface Contract

Five methods you must implement.

2. Custom Iterator

Build a range iterator.

3. The iterable Type (PHP 7.1+)

Accept both arrays and Traversable objects.

Generator Functions

A generator function uses `yield` to pause and resume execution. PHP automatically implements the `Iterator` interface for you — no class needed.

1. Basic Generator

yield pauses and returns a value.

2. yield with Keys

Yield key => value pairs.

3. Manual next() Calls

Control iteration manually via the Generator object.

Lazy Evaluation & Infinite Sequences

Generators are inherently lazy. They produce the next value only when the consumer asks, making them perfect for infinite sequences and large data streams.

1. Infinite Generator

Produce unbounded sequences without running out of memory.

2. Memory-Efficient File Reading

Stream large files line by line.

send(), return & yield from

Generators support two-way communication: the consumer can send values back in, retrieve the return value, and delegate to sub-generators.

1. send() — Two-Way Communication

Inject values into a running generator.

2. Generator Return Value (PHP 7.0+)

Retrieve the final return value after exhaustion.

3. yield from — Delegation (PHP 7.0+)

Delegate to another generator or iterable.

Real-World Use Cases

Generators are used throughout modern PHP for database pagination, pipeline processing, and batch operations.

1. Batch Processing

Process large datasets in chunks.

2. Generator Pipeline

Chain generators for step-by-step data transformation.