Anonymous, Callback and Arrow Functions
Pageturn wants each price doubled for a two-copy bundle, and only books under 10 shown in a "bargains" box. PHP's array_map and array_filter do the looping for you, but they need to be told what to do with each item. You tell them by handing over a function as a value.
The rule
A function can be a value: pass it in, and it gets called back.
A callback is a function you pass to another function, which calls it for you:
<?php
$prices = [9.99, 7.50, 12.00];
$doubled = array_map(fn($p) => $p * 2, $prices); // [19.98, 15, 24]
$bargains = array_filter($prices, fn($p) => $p < 10); // [9.99, 7.5]Note the argument order: array_map(callback, array) but array_filter(array, callback). It is a well-known PHP inconsistency, so check it every time.
There are three ways to write the function you pass:
1. An anonymous function (closure) has no name and is stored or passed directly. To use a variable from outside, list it with use. It is copied at the moment the closure is created:
$rate = 0.9;
$sale = function (float $p) use ($rate) {
return $p * $rate;
};
echo $sale(10); // 92. An arrow function (PHP 7.4) is the short form for a single expression: fn($p) => $p * $rate. It captures outside variables automatically, also by value, and returns the expression without a return keyword. It cannot contain multiple statements.
3. A named function as a string, such as array_map('strtoupper', $titles), uses an existing function as the callback.
Without use, a normal anonymous function cannot see $rate; it follows the same scope rule as any function.
The shortcut
Pick by size: one expression → fn; several statements → function () use (...); an existing function → pass its name.
What is done to each item?
Keep a price if it is under a limit. That is one expression, so use
fn.
Drills
Answer fast — trust the rule.
What does array_map(fn($p) => $p + 1, [1, 2, 3]) return?
A normal anonymous function needs $rate from outside. What must you add?
$rate = 0.9; $f = fn($p) => $p * $rate; $rate = 0.5; What is $f(10)?
Which call has its arguments in the correct order?
Remember
- A function can be a value: pass it in, and it gets called back.
- Shortcut: one expression →
fn; several statements →function () use (...). - Trap: closures copy outside values when created, and array_map and array_filter take their arguments in opposite orders.
