PHP Arrow Functions
Summary: in this tutorial, you will learn about PHP arrow functions and how to use them effectively.
Introduction to PHP arrow functions
PHP 7.4 introduced the arrow functions that provide a more concise syntax for the anonymous functions.
The following illustrates the basic syntax for arrow functions:
fn (arguments) => expression;
Code language: JavaScript (javascript)
In this syntax, an arrow function
- Start with the
fn
keyword. - Can have only one expression and return this expression.
The arrow function is functionally equivalent to the following anonymous function:
function(arguments) { return expression; }
Code language: JavaScript (javascript)
Unlike anonymous functions, arrow functions can automatically access variables from their parent scopes.
PHP arrow function examples
Let’s take some examples of using arrow functions.
1) Assign an arrow function to a variable
The following example illustrates how to assign an arrow function to a variable:
$eq = fn ($x, $y) => $x == $y;
echo $eq(100, '100'); // 1 (or true)
Code language: HTML, XML (xml)
How it works.
- First, define an arrow function and assign it to the $eq variable. The arrow function returns true if the two arguments are equal.
- Second, call the arrow function via the $eq variable
2) Pass an arrow function to a function example
The following example shows how to pass an arrow function to the array_map()
function:
$list = [10, 20, 30];
$results = array_map(
fn ($item) => $item * 2,
$list
);
print_r($results);
Code language: HTML, XML (xml)
Output:
Array
(
[0] => 20
[1] => 40
[2] => 60
)
Code language: PHP (php)
In this example, the array_map()
function applies the arrow function to every element of the $list
array and returns a new array that includes the results.
3) Return an arrow function from a function
The following example illustrates how to return an arrow function from a function:
function multiplier($x)
{
return fn ($y) => $x * $y;
}
$double = multiplier(2);
echo $double(10); // 200
Code language: HTML, XML (xml)
How it works.
- First, define a function called
multiplier()
that accepts an argument and returns an arrow function. Since the arrow function can access the variable from its parent scope, we can use the$x
parameter inside the arrow function. - Second, call the
multiplier()
function and assign the returned value to the$double
variable. The returned value of themultiplier()
function is a function, therefore, we can call it via the$double
variable.
Summary
- An arrow function provides a shorter syntax for writing a short anonymous function.
- An arrow function starts with the fn keyword and contains only one expression, which is the returned value of the function.
- An arrow function have the access to the variables in its parent scope automatically.