PHP Re-writing randomNumbers() using a generator


Example

Our randomNumbers() function can be re-written to use a generator.

<?php

function randomNumbers(int $length)
{
    for ($i = 0; $i < $length; $i++) {
        // yield tells the PHP interpreter that this value
        // should be the one used in the current iteration.
        yield mt_rand(1, 10);
    }
}

foreach (randomNumbers(10) as $number) {
    echo "$number\n";
}

Using a generator, we don't have to build an entire list of random numbers to return from the function, leading to much less memory being used.