What is an Arrow Function in PHP?
An arrow function (also called a “short closure”) is a new way to write anonymous functions in PHP. It’s much shorter and easier to read than the classic function
syntax.
When do we use Arrow Functions?
Use an arrow function when you want a quick and simple anonymous function, for example, when working with arrays or collections (array_map
, array_filter
, Laravel Collections, and so on).
How do you write an Arrow Function?
$sum = fn($a, $b) => $a + $b;
echo $sum(2, 3); // Outputs 5
The same with classic function syntax:
$sum = function($a, $b) {
return $a + $b;
};
echo $sum(2, 3); // Outputs 5
Main differences of Arrow Functions:
-
Short syntax:
fn($arg) => ...
- Always returns: The value on the right side is always returned.
-
No need for
use
: Arrow functions can see variables from outside by default.
Example using an outside variable:
$multiplier = 2;
$numbers = [1, 2, 3];
$result = array_map(fn($n) => $n * $multiplier, $numbers);
// [2, 4, 6]
When is it best to use Arrow Functions?
- Quick array operations
- In collection methods (Laravel)
- When you need very simple logic
When NOT to use Arrow Functions?
- If the function needs more than one statement (arrow functions only allow one expression)
- For complex logic, use the classic function
Other examples
Filter an array with an arrow function:
$users = [
['name' => 'Eka', 'age' => 25],
['name' => 'Gio', 'age' => 17],
];
$adults = array_filter($users, fn($user) => $user['age'] >= 18);
// Only Eka will stay in the array
Same with classic function:
$adults = array_filter($users, function($user) {
return $user['age'] >= 18;
});
Simple PHP example:
$nums = [1, 2, 3, 4, 5];
$squared = array_map(fn($n) => $n * $n, $nums);
// [1, 4, 9, 16, 25]
Can we use an Arrow Function directly when setting a variable’s value?
Yes! You can use an arrow function right when you set a variable’s value. For example:
$numbers = [2, 4, 8, 16];
$all_even = collect($numbers)->every(fn($n) => $n % 2 === 0);
// $all_even will be true if all numbers are even
Or with a simple array:
$users = [
['name' => 'Nika', 'age' => 21],
['name' => 'Lika', 'age' => 22],
];
$all_adult = array_reduce($users, fn($carry, $user) => $carry && $user['age'] >= 18, true);
// $all_adult will be true if all users are adults
Summary:
Arrow functions in PHP let you write very short and simple anonymous functions. They make your code cleaner when you need only one expression. You can use them for working with arrays, collections, and even when setting a variable’s value with a function result.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.