Generators with yield

Содержание
Your first generator
Why memory stays flat
Yield keys and values
When not to use them

Your first generator

A generator is a function that contains yield. Instead of returning once, it produces values one by one while the caller loops with foreach.

Each iteration resumes the function right after the previous yield.

function numbers(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } } foreach (numbers(3) as $n) { echo $n; }

Why memory stays flat

A normal function building a million item array must hold all values at once. A generator holds only the current value, so memory use stays flat while the count grows.

This makes generators ideal for reading large files and paginated API responses line by line.

function lines(string $path): Generator { $fh = fopen($path, "r"); while (($line = fgets($fh)) !== false) { yield trim($line); } fclose($fh); } foreach (lines("data.txt") as $line) { echo $line; }

Yield keys and values

Yield accepts an optional key before the value arrow. Callers then receive pairs just like from a normal array, which keeps downstream code unchanged.

Keys can be IDs, slugs, or line numbers that explain each value.

function users(): Generator { yield 1 => "Ada"; yield 2 => "Grace"; } foreach (users() as $id => $name) { echo $id; echo $name; }

When not to use them

Generators are forward only and cannot rewind without replaying the function. Counting, sorting, or random access needs a real array instead.

Use a generator for streaming and an array for repeated passes over small data.

$gen = numbers(5); var_dump(count(iterator_to_array($gen))); var_dump(is_countable(numbers(5)));

Next: Forms: GET and POST

Автор статьи: Arthur Isaev

Похожие статьи
Программирование на PHP
PHP course: zero to hero in 50 lessons
What is PHP and where it runs
Install PHP 8.5 and run your first command
Your first PHP script
Comments in PHP
Variables and constants
Types in PHP
Strings in PHP
Numbers in PHP
Operators
if and else
switch and match
Ternary, null coalescing and nullsafe
Loops
Arrays
Associative arrays
Functions
Variable scope
include and require
Namespaces
Composer and autoloading
Everyday string functions
Dates and time
JSON in PHP
Reading and writing files
Errors: read, reproduce, fix
Classes and objects
Constructors and promotion
Inheritance
Interfaces and traits
Enums
Magic methods
Attributes
Exceptions
Strict types
Closures and arrow functions
Generators with yield
Forms: GET and POST
HTTP: headers and status codes
Cookies
Sessions
Login with sessions
JSON REST endpoint
Database with PDO
Uploads and .htaccess
Lint like a pro
Clean functions
Debugging
Modern PHP tour: 5 to 8.4
PHP 8.5 for busy developers
Hero roadmap: the whole course on one page

Поиск по сайту

Канал @aofeed Чат @aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: