An arrow function is a shorter way to write a simple anonymous function. It starts with fn and uses => to point to the result. Arrow functions arrived in PHP 7.4.
Compare the two styles for the same job:
<?php
$numbers = [1, 2, 3];
// anonymous function
$doubled = array_map(function (int $n): int {
return $n * 2;
}, $numbers);
// arrow function
$doubled2 = array_map(fn(int $n): int => $n * 2, $numbers);
echo implode(", ", $doubled) . "\n";
echo implode(", ", $doubled2);
2, 4, 6
2, 4, 6
The arrow function has no { }, no return and no use. The result of the single expression is returned automatically.
Outside variables are captured automatically
A normal anonymous function needs use to see variables from outside. An arrow function sees them automatically, by value.
<?php
$taxRate = 0.18;
$prices = [100, 200];
$withTax = array_map(fn($price) => $price * (1 + $taxRate), $prices);
echo implode(", ", $withTax);
118, 236
Limits
- The body is one expression only. For several statements, use a normal anonymous function.
- Captured variables are copied. Changing them inside the function does not change the outside variable.
<?php
$count = 0;
$increase = fn() => $count++;
$increase();
echo $count;
0
Sorting with an arrow function
<?php
$users = [
["name" => "Zoya", "age" => 30],
["name" => "Ali", "age" => 22],
];
usort($users, fn($a, $b) => $a["age"] <=> $b["age"]);
echo $users[0]["name"];
Ali
Filtering
<?php
$words = ["php", "go", "javascript", "c"];
$long = array_filter($words, fn($w) => strlen($w) > 2);
echo implode(", ", $long);
php, javascript
Nesting
Arrow functions can contain another arrow function. The inner one also sees the outer variables.
<?php
$add = fn($x) => fn($y) => $x + $y;
echo $add(3)(4);
7
Use them for short callbacks
array_map, array_filter and usort with a single-line rule are the perfect home for fn. If it needs a second line, switch to a normal function.