Use PHP's Generators for Memory-Efficient Data Processing

Use PHP's Generators for Memory-Efficient Data Processing

Generators are excellent for working with large datasets or infinite sequences without loading everything into memory at once.

function getLines($file) {
    $f = fopen($file, 'r');
    try {
        while ($line = fgets($f)) {
            yield $line;
        }
    } finally {
        fclose($f);
    }
}

// Usage
foreach (getLines('large_file.txt') as $line) {
    echo $line;
}

This generator function reads a file line by line, yielding each line. It's memory-efficient for processing large files that wouldn't fit into memory all at once.

← Back to Tips List