Anonymous functions, array_map and week 4 review
In PHP functions are also values: you can store them in a variable, pass them as an argument and return them from another function. This opens the door to a very expressive style of programming with arrays. Instead of writing a foreach for every transformation, you use functions like array_map, array_filter and array_reduce and hand them a small function that says what to do with each element. We close the week with this topic and a review of everything about functions.
Closures and arrow functions
An anonymous function (closure) has no name and is assigned to a variable. To use outside variables you must declare them with use, and they are copied at the moment it is created. The arrow function, written with fn, is a short single-expression form that captures outside variables automatically by value. Use it for simple operations; if you need several statements, use a normal closure. Both can be called with parentheses, like any function: $double(4).
<?php
declare(strict_types=1);
$rate = 0.21;
$withTax = function (float $price) use ($rate): float {
return round($price * (1 + $rate), 2);
};
echo $withTax(100.0), "\n"; // 121
$double = fn(int $n): int => $n * 2; // arrow function
echo $double(4), "\n"; // 8
$bonus = 5;
$addBonus = fn(int $n): int => $n + $bonus; // $bonus captured automatically
echo $addBonus(10), "\n"; // 15array_map, array_filter and array_reduce
array_map applies a function to each element and returns a new array with the results. array_filter keeps only the elements for which the function returns true; it keeps the original keys, so use array_values if you need to reindex. array_reduce reduces the array to a single value by accumulating: it takes the function, the array and the initial value. None of them modifies the original array, which avoids many bugs. Check the argument order: array_map takes the function first, but array_filter takes the array first.
<?php
declare(strict_types=1);
$products = [
['name' => 'Pen', 'price' => 1.5, 'qty' => 10],
['name' => 'Book', 'price' => 12.0, 'qty' => 2],
['name' => 'Bag', 'price' => 30.0, 'qty' => 0],
];
$names = array_map(fn(array $p): string => $p['name'], $products);
print_r($names); // [Pen, Book, Bag]
$inStock = array_values(array_filter($products, fn(array $p): bool => $p['qty'] > 0));
echo count($inStock), "\n"; // 2
$total = array_reduce(
$products,
fn(float $carry, array $p): float => $carry + $p['price'] * $p['qty'],
0.0
);
echo $total, "\n"; // 39
// Sort by price descending using the spaceship operator
usort($products, fn(array $a, array $b): int => $b['price'] <=> $a['price']);
echo $products[0]['name'], "\n"; // Bag
// array_column extracts one field
echo implode(', ', array_column($products, 'name')), "\n"; // Bag, Book, PenA style tip: chaining several array functions can produce unreadable lines. When a transformation has more than two steps, store each intermediate result in a variable with a clear name, or extract the logic into a named function. A ten-line anonymous function inside array_map is a sign it deserves its own name. And remember: to walk an array just to produce an effect, such as printing text, a foreach is still clearer than array_map.
Also practice the spaceship operator <=>, which returns -1, 0 or 1 depending on whether the first value is less than, equal to or greater than the second. It is the basis of any comparison function for usort, uasort or uksort, and it works the same with numbers and with text.
理解度チェック
問題 1 / 6How does an arrow function (fn) capture outside variables?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字