The yield keyword helps create simple functions that produce values one at a time, saving memory and making code easier to read.
0
0
Yield keyword behavior in PHP
Introduction
When you want to process large lists without loading everything into memory at once.
When you need to generate a sequence of values step-by-step, like numbers or data from a file.
When you want to pause a function and resume it later to produce the next value.
When you want to write cleaner code instead of building and returning big arrays.
When you want to improve performance by producing values on demand.
Syntax
PHP
<?php function generatorFunction() { yield 1; }
yield pauses the function and sends a value back to the caller.
Each time the generator is called again, it resumes right after the last yield.
Examples
This function yields numbers 1, 2, and 3 one by one.
PHP
<?php function countToThree() { yield 1; yield 2; yield 3; }
This generator yields letters instead of numbers.
PHP
<?php function letters() { yield 'a'; yield 'b'; yield 'c'; }
This generator yields squares of numbers from 1 up to
$max.PHP
<?php function squares($max) { for ($i = 1; $i <= $max; $i++) { yield $i * $i; } }
Sample Program
This program uses a generator to yield two words, printing each on its own line.
PHP
<?php function simpleGenerator() { yield 'Hello'; yield 'World'; } foreach (simpleGenerator() as $word) { echo $word . "\n"; }
OutputSuccess
Important Notes
Generators created with yield are memory efficient because they don't build the whole list at once.
You can use foreach to loop over values yielded by the generator.
Generators can also receive values back using yield with keys or by sending values, but that is more advanced.
Summary
Yield lets functions produce values one at a time.
It helps save memory and write cleaner code for sequences.
Use foreach to get each yielded value step-by-step.