Use Arrow Function in PHP with examples

- 9 mins

Arrow function in PHP

It is available since PHP version 7.4 but many do not understand how to use it.

Arrow functions, also known as “short closures”, were introduced in PHP 7.4 as a more concise way to define anonymous functions. They are particularly useful for small, simple functions.

Probably if you come from other languages you are already used to using them but if this is not your case I encourage you to continue reading the article where I show you some examples of use.

How to use Arrow Function

Arrow functions are defined using the fn keyword, followed by the function parameters, the arrow (=>) symbol, and the function body.

Here we can see a basic example of how to implement it.

// Anonymous function
$add = function($a, $b) {
    return $a + $b;
};

// Arrow function
$addArrow = fn($a, $b) => $a + $b;

echo $add(2, 3);        // Output: 5
echo $addArrow(2, 3);   // Output: 5

Arrow functions can also capture variables from the surrounding scope, unlike traditional closures, arrow functions do not need to be explicitly defined variables from scope.

$factor = 10;

// Closure
$multiplier = function($n) use ($factor) {
    return $n * $factor;
};

// Arrow function
$multiplierArrow = fn($n) => $n * $factor;

echo $multiplier(5);        // Output: 50
echo $multiplierArrow(5);   // Output: 50

Examples

Now that we have seen how to define an arrow function in PHP, let’s see some examples of how to use them.

In the examples we can see that both the traditional anonymous function and the arrow function achieve the same result.

Using Arrow Functions in Array Map

They square each number in the input array using the array_map function.

“Applies the callback to the elements of the given arrays”

array_map(?callable $callback, array $array, array ...$arrays): array

$numbers = [1, 2, 3, 4, 5];

// Anonymous function with array_map
$squared = array_map(function($n) {
    return $n * $n;
}, $numbers);

// Arrow function with array_map
$squaredArrow = array_map(fn($n) => $n * $n, $numbers);

print_r($squared);
print_r($squaredArrow);

// Output:
//Array
//(
//  [0] => 1
//  [1] => 4
//  [2] => 9
//  [3] => 16
//  [4] => 25
//)
//Array
//(
//  [0] => 1
//  [1] => 4
//  [2] => 9
//  [3] => 16
//  [4] => 25
//)

Using Arrow Functions with Array Filter

We filter all the even numbers of an array using the array_filter function.
Filters elements of an array using a callback function

Filters elements of an array using a callback function

array_filter(array $array, ?callable $callback = null, int $mode = 0): array

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Anonymous function with array_filter
$evenNumbers = array_filter($numbers, function($n) {
    return $n % 2 === 0;
});

// Arrow function with array_filter
$evenNumbersArrow = array_filter($numbers, fn($n) => $n % 2 === 0);

print_r($evenNumbers);
print_r($evenNumbersArrow);

// Output:
//Array
//(
//  [1] => 2
//  [3] => 4
//  [5] => 6
//  [7] => 8
//  [9] => 10
//)
//Array
//(
//  [1] => 2
//  [3] => 4
//  [5] => 6
//  [7] => 8
//  [9] => 10
//)

Using Arrow Functions with Array Reduce

We sum all values in array with callback function using the array_reduce function.

“Iteratively reduce the array to a single value using a callback function”

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

$numbers = [1, 2, 3, 4, 5];

// Anonymous function with array_reduce
$sumNumbers = array_reduce($numbers, function($carry, $number) {
    return $carry + $number;
}, 0);

// Arrow function with array_reduce
$sumNumbersArrow = array_reduce($numbers, fn($carry, $number) => $carry + $number, 0);

echo $sumNumbers;       // Output: 15
echo $sumNumbersArrow;  // Output: 15

Using Arrow Functions with usort

Arrow functions can be used in various contexts, including callbacks for array by reference functions like usort. Sort the array by age.

“Sort an array by values using a user-defined comparison function”

usort(array &$array, callable $callback): true

$people = [
    ['name' => 'Alice', 'age' => 28],
    ['name' => 'Bob', 'age' => 22],
    ['name' => 'Charlie', 'age' => 25],
];

// Sorting using usort with anonymous function
usort($people, function($a, $b) {
    return $a['age'] <=> $b['age'];
});

// Sorting using arrow function
usort($people, fn($a, $b) => $a['age'] <=> $b['age']);

print_r($people);

// Output:
//Array
//(
//  [0] => Array
//      (
//          [name] => Bob
//          [age] => 22
//      )
//
//  [1] => Array
//      (
//          [name] => Charlie
//          [age] => 25
//      )
//
//  [2] => Array
//    (
//      [name] => Alice
//      [age] => 28
//    )
//
//)

I think that with these examples we can see how to implement the arrow functions in the most common cases.

If you think that I have left some or you have some doubt about some case, leave me a comment :-)

Conclusion

Arrow functions were introduced in PHP 7.4 as a more concise way to define anonymous functions. They offer several advantages, but also have some limitations. Here are the pros and cons of using arrow functions in PHP:

Pros:

Cons:

Choosing Between Arrow Functions and Traditional Closures:

In summary, arrow functions can be a powerful tool for writing concise and readable code for simple operations. However, it’s important to be aware of their limitations and choose the appropriate tool based on the specific context and complexity of your code.

You can read the article on Medium

Albert Colom

Albert Colom

Backend developer