PHP Generators.

PHPServer Side ProgrammingProgramming

PHP Online Training

45 Lectures 9 hours

PHP in Telugu

43 Lectures 5.5 hours

Redis and PHP

22 Lectures 40 mins

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){

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 09:15:49