An Essential Guide to PHP Arrow Functions By Examples (original) (raw)

Skip to content

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:

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(eq = fn (eq=fn(x, y)=>y) => y)=>x == $y;

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

Try it

How it works.

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∗x * xy; }

$double = multiplier(2);

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

Try it

Output:

20Code language: PHP (php)

How it works.

Summary #

Did you find this tutorial useful?