In PHP, how do I stream arrays with examples?

In PHP, you can stream arrays efficiently by utilizing generators, which allow you to yield values one at a time without needing to load the entire array into memory. This approach is beneficial for handling large datasets.

php, stream arrays, generators, yield, memory efficient
Learn how to stream arrays in PHP using generators to efficiently handle large datasets and improve memory management.

// Example of streaming arrays with a generator in PHP

function streamArray(array $data) {
    foreach ($data as $item) {
        yield $item; // Yield each item one by one
    }
}

$data = range(1, 100); // Example array from 1 to 100
$streamedData = streamArray($data); // Create a generator

foreach ($streamedData as $value) {
    echo $value . PHP_EOL; // Process each item as it is yielded
}
    

php stream arrays generators yield memory efficient