0
0
PHPprogramming~5 mins

Generator function execution model in PHP

Choose your learning style9 modes available
Introduction

A generator function lets you pause and resume code, producing values one at a time without using lots of memory.

When you want to handle large lists without loading everything into memory.
When you want to create a sequence of values step-by-step.
When you want to write cleaner code that produces values on demand.
When you want to process data streams efficiently.
When you want to pause a function and continue later.
Syntax
PHP
<?php
function generatorName() {
    yield $value;
}

The yield keyword pauses the function and sends a value out.

Each time you call next() on the generator, it resumes from where it paused.

Examples
This generator yields numbers 1, 2, and 3 one by one.
PHP
<?php
function countToThree() {
    yield 1;
    yield 2;
    yield 3;
}
This generator yields letters 'a', 'b', and 'c' step-by-step.
PHP
<?php
function letters() {
    yield 'a';
    yield 'b';
    yield 'c';
}
Sample Program

This program creates a generator that yields two strings. The foreach loop gets each value and prints it on a new line.

PHP
<?php
function simpleGenerator() {
    yield 'Hello';
    yield 'World';
}

$generator = simpleGenerator();
foreach ($generator as $value) {
    echo $value . "\n";
}
OutputSuccess
Important Notes

Generators save memory because they produce one value at a time instead of all at once.

You can use foreach to loop over generator values easily.

Generators can be paused and resumed, unlike normal functions that run all at once.

Summary

Generators use yield to pause and send values one by one.

They help handle large or infinite sequences efficiently.

Use foreach to get values from a generator.