Generators & Iterators in PHP

From the PHP cheat sheet · Advanced Features · verified Jul 2026

Generators & Iterators

Memory-efficient iteration with generators

php
// Simple generator
function getNumbers() {
    for ($i = 1; $i <= 3; $i++) {
        yield $i;
    }
}

foreach (getNumbers() as $number) {
    echo $number;
}

// Generator with keys
function getUsers() {
    yield 'admin' => 'Alice';
    yield 'user' => 'Bob';
}
💡 Generators use yield to pause and resume execution
⚡ Perfect for processing large datasets with low memory
📌 yield from delegates to another generator
🔥 Generators maintain state between iterations

More PHP tasks

Back to the full PHP cheat sheet