0
0
PHPprogramming~5 mins

Memory efficiency with generators in PHP

Choose your learning style9 modes available
Introduction

Generators help save memory by producing values one at a time instead of all at once.

When working with large lists or files that don't fit in memory.
When you want to process data step-by-step without loading everything.
When you want to improve performance by avoiding big memory use.
When reading large logs or streams line by line.
When you want to create simple iterators without extra memory cost.
Syntax
PHP
<?php
function generatorName() {
    yield 'value1';
    yield 'value2';
    // more yields
}

foreach (generatorName() as $item) {
    // use $item
}
?>

yield pauses the function and returns a value each time.

Generators do not store all values in memory at once.

Examples
This generator yields numbers 1 to 3 one by one.
PHP
<?php
function countToThree() {
    yield 1;
    yield 2;
    yield 3;
}

foreach (countToThree() as $number) {
    echo $number . "\n";
}
This generator yields numbers from 5 to 7 using a loop.
PHP
<?php
function rangeGenerator($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

foreach (rangeGenerator(5, 7) as $num) {
    echo $num . "\n";
}
Sample Program

This program uses a generator to print numbers from 1 to 5 without storing them all at once.

PHP
<?php
function bigRange($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

foreach (bigRange(1, 5) as $value) {
    echo "Value: $value\n";
}
OutputSuccess
Important Notes

Generators are great for saving memory with big data.

Each yield returns one value and pauses the function.

You can loop over generators just like arrays.

Summary

Generators produce values one at a time to save memory.

Use yield inside functions to create generators.

Generators help handle large data efficiently.