This function is using yield:
function a($items) {
foreach ($items as $item) {
yield $item + 1;
}
}
It is almost the same as this one without:
function b($items) {
$result = [];
foreach ($items as $item) {
$result[] = $item + 1;
}
return $result;
}
The only one difference is that a()
returns a generator and b()
just a simple array. You can iterate on both.
Also, the first one does not allocate a full array and is therefore less memory-demanding.