PHP Generators and yield

PHP generators allows you to iterate through data by using less memory compared to a standard foreach function. Simple example: If you want to display the numbers between 1 and 5000000 with a simple foreach you may hit the memory limits used by PHP.

echo 'Use range and foreach to display numbers from 1 to 5000000';
foreach (range(1, 5000000) as $number) {
    echo "$number <br />";
}

This code will produce an error in my environment: Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 268435464 bytes. The reason is that your machine is trying to create an array with elements from 1 to 5000000 which eats up your allocated memory. In order to avoid this you can use generator that will skip allocating the memory for this huge array.

The magic word is yield which is similar to return but it will not return the huge array with 5000000 elements but it will return the elements one by one:

function range_with_generator($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

echo 'Range with generator';
foreach (range_with_generator(1, 5000000) as $number) {
    echo $number.'<br />';
}

Here yield will return the number and continie with the next one which actually contributes to using less memory. Thus the above program will be executable in my environment and it will successfully print the numbers without consuming all of the memory.

Leave a Reply

Your email address will not be published. Required fields are marked *