PHP closures, array functions, and generators
PHP has first-class functions. An arrow function, fn($x) => $x * 2, is a short closure that captures variables from the surrounding scope automatically by value. A full closure, function () use ($rate) { ... }, lists the variables it captures, and use (&$total) captures by reference so the closure can change the outer variable. array_map, array_filter, and array_reduce apply a function across an array.
PHP
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$squares = array_map(fn($n) => $n * $n, $numbers);
$evens = array_filter($squares, fn($n) => $n % 2 === 0);
$sum = array_reduce($evens, fn($carry, $n) => $carry + $n, 0);
echo implode(",", $squares), " | ", implode(",", $evens), " | ", $sum, "\n";
$rate = 3;
$multiply = function (int $n) use ($rate) {
return $n * $rate;
};
echo $multiply(5), "\n";
$total = 0;
array_walk($numbers, function ($n) use (&$total) {
$total += $n;
});
echo $total, "\n";
function fibonacci(): Generator
{
[$a, $b] = [0, 1];
while (true) {
yield $a;
[$a, $b] = [$b, $a + $b];
}
}
$first = [];
foreach (fibonacci() as $value) {
if (count($first) === 10) {
break;
}
$first[] = $value;
}
echo implode(" ", $first), "\n";