PHP Generators.


Introduction

Traversing a big collection of data using looping construct 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 is used inside a generator function

Example

 Live Demo

<?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

Output

1 4 9 16 25

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

Example

 Live Demo

<?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

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

2 4 6 8 10

An associative array can also be implemented as generator

Example

 Live Demo

<?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 . "
"; ?>

Output

one=>1
two=>2
three=>3
four=>4

Updated on: 18-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements