PHP Generators.

Traversing a big collection of data using looping constructs such as foreach would require large memory and considerable processing time. With generators it is possible to iterate over a set of data without these overheads. A generator function is similar to a normal function. However, instead of return statement in a function, generator uses yield keyword to be executed repeatedly so that it provides values to be iterated.

The yield keyword is the heart of generator mechanism. Even though its use appears to be similar to return, it doesn't stop execution of function. It provides next value for iteration and pauses execution of function.

Yielding Values

A for loop yields each value of looping variable inside a generator function −

<?php
function squaregenerator(){
    for ($i=1; $i<=5; $i++){
        yield $i*$i;
    }
}
$gen=squaregenerator();
foreach ($gen as $val){
    echo $val . " ";
}
?>

As foreach statement tries to display $val for first time, the squaregenerator yields first element, retains $i and pauses execution till foreach takes next iteration. The output is similar to a regular foreach loop −

1 4 9 16 25 

Generator for Range Function

PHP's range() function returns a list of integers from $start to $stop with interval of $step between each numbers. Following program implements range() as generator −

<?php
function rangegenerator($start, $stop, $step){
    for ($i=$start; $i<=$stop; $i+=$step){
        yield $i;
    }
}
foreach (rangegenerator(2,10,2) as $val){
    echo $val . " ";
}
?>

Output is similar to range(2,10,2)

2 4 6 8 10 

Generator for Associative Arrays

An associative array can also be implemented as generator −

<?php
function arrgenerator($arr){
    foreach ($arr as $key=>$val){
        yield $key=>$val;
    }
}
$arr=array("one"=>1, "two"=>2, "three"=>3, "four"=>4);
$gen=arrgenerator($arr);
foreach ($gen as $key=>$val)
    echo $key . "=>" . $val . "<br>";
?>
one=>1
two=>2
three=>3
four=>4

Key Benefits

Generators offer significant memory efficiency by processing one item at a time instead of loading entire datasets into memory. They are particularly useful for handling large files or database results.

Conclusion

PHP generators provide an elegant solution for memory-efficient iteration over large datasets. Using the yield keyword, you can create functions that pause and resume execution, making them ideal for processing large amounts of data without overwhelming system resources.

Updated on: 2026-03-15T09:11:18+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements