Tutorial by Examples

Generators are useful when you need to generate a large collection to later iterate over. They're a simpler alternative to creating a class that implements an Iterator, which is often overkill. For example, consider the below function. function randomNumbers(int $length) { $array = []; ...
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...
One common use case for generators is reading a file from disk and iterating over its contents. Below is a class that allows you to iterate over a CSV file. The memory usage for this script is very predictable, and will not fluctuate depending on the size of the CSV file. <?php class CsvReade...
A yield statement is similar to a return statement, except that instead of stopping execution of the function and returning, yield instead returns a Generator object and pauses execution of the generator function. Here is an example of the range function, written as a generator: function gen_one_t...
Generators are fast coded and in many cases a slim alternative to heavy iterator-implementations. With the fast implementation comes a little lack of control when a generator should stop generating or if it should generate something else. However this can be achieved with the usage of the send() fu...

Page 1 of 1