Introduced in PHP 7.4, arrow functions (also known as short closures) are a more concise way of writing anonymous functions. They are particularly useful for single-line operations and callback functions.
An arrow function uses the fn keyword instead of function and is limited to a single expression. It automatically returns the result of that expression.
<?php
$y = 10;
// Arrow function
$fn1 = fn($x) => $x + $y;
echo $fn1(5); // Outputs: 15
?>
One of the biggest advantages of arrow functions is that they automatically capture variables from the parent scope. In a traditional anonymous function, you would need to use the use keyword to do this.
<?php
$factor = 10;
// Traditional Anonymous Function
$multiplySimple = function($n) use ($factor) {
return $n * $factor;
};
// New Arrow Function
$multiplyArrow = fn($n) => $n * $factor;
echo $multiplyArrow(5); // Outputs: 50
?>
Arrow functions are best suited for passing small pieces of logic into internal PHP functions like array_map(), array_filter(), or usort().
<?php
$numbers = [1, 2, 3, 4];
$squared = array_map(fn($n) => $n * $n, $numbers);
print_r($squared); // [1, 4, 9, 16]
?>
fn keyword and the => arrow.