Arrow functions
Like a closure, only slimmer
- Added in: PHP 7.4
- What it gives you: a compact syntax for short functions that automatically see variables from the surrounding scope and always return a result.
Things you need to know
- they always return a value;
- they can contain only a single expression — no
{}and no multi-statement blocks; - they automatically inherit variables from the surrounding scope, without
use($x); - they read as an expression, not as a statement.
Why it's convenient
- less boilerplate;
- expressiveness in callbacks (map, filter, reduce);
- better readability, especially in collections and streams;
- a fit for any place where you need a minimal handler.
Real-world examples
Transforming an array
$prices = [100, 200, 300];
$tax = 0.2;
// ❌ A regular anonymous function
$withTax = array_map(function (int $p) use ($tax) {
return $p * (1 + $tax);
}, $prices);
// ✅ An arrow function
$withTax = array_map(fn(int $p) => $p * (1 + $tax), $prices);
Filtering elements
$activeUsers = array_filter($users, fn(User $u) => $u->active);
Computing a value
$total = array_reduce($orders, fn(int $sum, Order $o) => $sum + $o->amount, 0);
A simple calculator with access to an outer variable
$multiplier = 3;
$calc = fn(int $v) => $v * $multiplier;
echo $calc(10); // 30
Conclusion
Arrow functions are a concise form of closures, made for clean, short expressions in straightforward logic.
If your code has function ($x) use ($y) { return …; } — just replace it with fn() and feel the difference.
← Previous: Anonymous classes · Whole series · Next: Generators →
First published in Ukrainian in the Telegram channel “Created to die” on October 17, 2025.