Infinite generators
Learn generators that produce infinite sequences and using them in finite loops.
Infinite generators
You can write a generator that produces values forever with while (true). Memory does not fill up because only one value is produced at a time; earlier values are not stored.
To use an infinite generator in a finite loop, you stop with break or take a fixed number of steps. Otherwise foreach would run forever.
Using an infinite generator finitely
If you iterate an infinite generator with foreach, the loop never stops. You stop it with break under a condition, for example after a fixed number of values.
This way you take only what you need from an infinite stream. The generator stops and memory releases; remaining values are never computed.
Exercise First 5 numbers with naturals
Write naturals(): \Generator: starting from 1, produce numbers forever with while (true), incrementing after each yield. Iterate naturals() with foreach; print the first 5 numbers, then stop with break.
Show example solution
In naturals, start with $n = 1, then in while (true) yield $n; and $n++. Iterate with foreach (naturals() as $n), keep a $count counter; break when $count >= 5.
Example solution:
<?php
function naturals(): \Generator {
$n = 1;
while (true) {
yield $n;
$n++;
}
}
$count = 0;
foreach (naturals() as $n) {
echo $n . "\n";
$count++;
if ($count >= 5) {
break;
}
}
Test yourself
-
What happens when an infinite generator with while (true) is called?
- All values are produced until memory overflows
- No value is ever produced
- Only the first value is returned
- One value is produced per request, forever
Show answer
One value is produced per request, forever — Correct. A generator is lazy; one value is produced per request and memory does not fill.
-
Infinite loop in the naturals generator
function naturals(): \Generator { $n = 1; ____ { yield $n; $n++; } }Show answer
function naturals(): \Generator { $n = 1; while (true) { yield $n; $n++; } } -
Match the infinite generator concepts
- while (true)
- Starts an infinite loop
- yield
- Produces a value each iteration
- break
- Stops the loop
- foreach
- Iterates the generator