Tsallaka zuwa abun ciki
Justice Tech School

Recursion and Generators

A function can call itself. Generators use yield to produce values one at a time, saving memory for large sequences.

Example
function fact($n) { return $n <= 1 ? 1 : $n * fact($n - 1); }
echo fact(6), "\n";
function counter($max) { for ($i = 1; $i <= $max; $i++) yield $i; }
foreach (counter(3) as $n) echo $n, " ";
echo "\n";
function pairs() { yield "a" => 1; yield "b" => 2; }
foreach (pairs() as $k => $v) echo "$k=$v ";
echo "\n";

Result

720
1 2 3 
a=1 b=2 

Exercise

Produce a value lazily.

 $i;

Quiz Test

What is a generator for?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.