PHP Arrow Functions
August 19, 2022 ‐ 1 min read
With version 7.4 PHP introduced arrow functions, which are anonymous functions with a shorter syntax. Anonymous functions mostly come in handy for callback functions, when filtering an array for example:
<?php
$numbers = [-4, 1, 8, 0];
$positive = array_filter($numbers, fn($n) => $n >= 1);
//=> [1, 8]
Arrow functions are defined using the fn
keyword and can only have one expression, for which the result is used as the return value. Therefore there is no need for the return
statement, it's not even allowed actually.
Arrow functions differ from anonymous functions in that they don't require the use
keyword in order to use variables from outside the function scope.