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 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: PHP (php)

In this syntax, an arrow function:

  • Starts 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: PHP (php)

Unlike anonymous functions, arrow functions can access variables from their parent scopes.

Assigning an arrow function to a variable #

The following example illustrates how to assign an arrow function to a variable:

<?php

$eq = fn ($x, $y) => $x == $y;

echo $eq(100, '100'); // 1 (or true)Code language: PHP (php)

Try it

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

Passing an arrow function to a function example #

The following example shows how to pass an arrow function to the array_map() function:

<?php

$list = [10, 20, 30];

$results = array_map(
	fn ($item) => $item * 2,
	$list
);

print_r($results);Code language: PHP (php)

Try it

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.

Returning an arrow function from a function #

The following example illustrates how to return an arrow function from a function:

<?php

function multiplier($x)
{
	return fn ($y) => $x * $y;
}

$double = multiplier(2);

echo $double(10);Code language: PHP (php)

Try it

Output:

20Code language: PHP (php)

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 the multiplier() 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, the function’s return value.
  • An arrow function has access to the variables in its parent scope automatically.
Did you find this tutorial useful?