Range Over Channels in PHP
In a previous example, we saw how foreach
provides iteration over basic data structures. We can also use this syntax to iterate over values received from a generator function, which is similar to how channels work in some other languages.
<?php
// We'll iterate over 2 values in the `queue` generator.
function queue() {
yield "one";
yield "two";
}
// This `foreach` iterates over each element as it's
// received from `queue()`. The iteration terminates
// after receiving the 2 elements.
foreach (queue() as $elem) {
echo $elem . "\n";
}
To run the program, save it as range-over-generator.php
and use php
:
$ php range-over-generator.php
one
two
This example demonstrates how we can use generators in PHP to create a sequence of values that can be iterated over. The yield
keyword is used to define generator functions, which can be thought of as a way to create lazy iterators.
While PHP doesn’t have built-in channels like some other languages, generators provide a similar concept for producing a sequence of values that can be consumed on-demand. The foreach
loop automatically handles the iteration over the generator, making it easy to process the yielded values.
This approach is memory-efficient for large datasets or when dealing with I/O operations, as it allows you to generate values one at a time instead of creating the entire sequence in memory at once.