Since PHP 5.5 was implemented in the Generator language. It can be used inside a function from the keyword yield
.
In the Manual , we have an example where one is compared to the function range(0, 1000000)
(which theoretically it would spend 100MB of memory) and a xrange
implementation through generators (which would reduce memory consumption to 1 kilobyte).
Example of the manual:
<?php
function xrange($start, $limit, $step = 1) {
if ($start < $limit) {
if ($step <= 0) {
throw new LogicException('Step must be +ve');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be -ve');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}
/*
* Note that both range() and xrange() result in the same
* output below.
*/
echo 'Single digit odd numbers from range(): ';
foreach (range(1, 9, 2) as $number) {
echo "$number ";
}
echo "\n";
echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
echo "$number ";
}
?>
In addition to the benefit of saving this memory and simplifying the use of an iterator , what are the other advantages of using generator in PHP?