{
    "slug": "php_generators",
    "term": "PHP Generators",
    "category": "php",
    "difficulty": "intermediate",
    "short": "Functions using yield that produce values lazily — one at a time — instead of building a complete array in memory.",
    "long": "A generator function uses yield to return values one at a time, pausing execution between yields. The caller receives a Generator object implementing Iterator. Generators consume O(1) memory regardless of the sequence length — ideal for large datasets, file streaming, and infinite sequences. yield from delegates to another generator or iterable. send() passes values back into a paused generator. PHP 5.5+ supports generators; PHP 7.0 added return values from generators.",
    "aliases": [
        "PHP yield",
        "generator function PHP",
        "lazy evaluation PHP",
        "PHP iterator"
    ],
    "tags": [
        "php",
        "performance",
        "memory"
    ],
    "misconception": "Generators are only useful for infinite sequences. Generators benefit any situation where you need to process a large dataset without loading it all into memory at once.",
    "why_it_matters": "Loading a 1M-row CSV into an array requires hundreds of MB of RAM. A generator processes it line by line in constant memory — the difference between a working script and an out-of-memory crash.",
    "common_mistakes": [
        "Calling a generator function and expecting an array — it returns a Generator object; use foreach or iterator_to_array().",
        "Using iterator_to_array() on a large generator — defeats the memory benefit by materialising the full sequence.",
        "Not using yield from when composing generators — manually looping and yielding is verbose and slower."
    ],
    "when_to_use": [
        "Use generators for processing large files, database result sets, or API pagination where loading everything at once would exhaust memory.",
        "Use generators when you need a lazy sequence — producing values only when requested."
    ],
    "avoid_when": [
        "Do not use generators when you need random access to elements — generators are forward-only.",
        "Avoid calling iterator_to_array() on a generator for large datasets — it loads the full sequence into memory."
    ],
    "related": [
        "php_memory_model",
        "php_fiber_internals"
    ],
    "prerequisites": [],
    "refs": [
        "https://www.php.net/manual/en/language.generators.php"
    ],
    "bad_code": "// Loads entire CSV into memory — crashes on large files\nfunction readCsvRows(string $file): array {\n    $rows = [];\n    $handle = fopen($file, 'r');\n    while (($row = fgetcsv($handle)) !== false) {\n        $rows[] = $row; // 1M rows = hundreds of MB RAM\n    }\n    return $rows;\n}",
    "good_code": "// Generator: reads CSV line by line — O(1) memory\nfunction readCsvRows(string $file): \\Generator {\n    $handle = fopen($file, 'r');\n    while (($row = fgetcsv($handle)) !== false) {\n        yield $row;\n    }\n    fclose($handle);\n}\n\nforeach (readCsvRows('million_rows.csv') as $row) {\n    processRow($row); // only one row in memory at a time\n}",
    "quick_fix": "Replace array-returning functions that process large datasets with generators using yield",
    "effort": "low",
    "created": "2026-03-31",
    "updated": "2026-03-31",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/php_generators",
        "html_url": "https://codeclaritylab.com/glossary/php_generators",
        "json_url": "https://codeclaritylab.com/glossary/php_generators.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[PHP Generators](https://codeclaritylab.com/glossary/php_generators) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/php_generators"
            }
        }
    }
}