Re-writing randomNumbers using a generator

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Generators:
* Re-writing randomNumbers using a generator

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
32 Generators
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR