How can Generators in PHP be utilized to save memory when working with large datasets or streams?

Generators in PHP can be utilized to save memory when working with large datasets or streams by allowing you to iterate over a large dataset without loading it all into memory at once. Instead of storing the entire dataset in an array, you can use a generator to yield each item one at a time, reducing memory usage.

function largeDataSetGenerator() {
    // Simulate a large dataset
    for ($i = 0; $i < 1000000; $i++) {
        yield $i;
    }
}

// Iterate over the generator without loading the entire dataset into memory
foreach (largeDataSetGenerator() as $item) {
    // Process each item
    echo $item . "\n";
}