Foreach in PHP: How to Use Generators

PHOTO EMBED

Sat Jun 28 2025 13:32:12 GMT+0000 (Coordinated Universal Time)

Saved by @Samuel88 #php

function getNumbers() {
    for ($i = 1; $i <= 1000000; $i++) {
        yield $i;
    }
}

foreach (getNumbers() as $number) {
    if ($number > 5) break;
    echo "$number\n";
}
content_copyCOPY

This code has a function named getNumbers(). Inside it, there is a for loop that counts from 1 to 1,000,000. Instead of building a big list, yield sends out each number one at a time when the loop outside asks for it. The foreach loop goes through these numbers. It starts with 1 and prints each number. When the number becomes more than 5, the break stops the loop. So this will only print numbers 1 to 5.

https://flatcoding.com/tutorials/php/foreach-loop-in-php/