PHP Arrow Functions : A Tutorial with Examples

Arrow functions in PHP, introduced in PHP 7.4, provide a shorter and more concise syntax for anonymous functions (also known as closures).

They offer a simple and convenient way to write functions, particularly when dealing with small and single-expression logic.

In this tutorial, we will cover:

Let’s explore each of these topics with examples and explanations.

1. What is an Arrow Function?

An arrow function is a shorthand syntax for defining an anonymous function in PHP.

It allows for a more compact form of function declarations and is particularly useful in cases where the function body is simple and returns a single value.

Arrow functions automatically capture variables from the parent scope, eliminating the need for the use keyword in closures.

Key Features of Arrow Functions:

  • They use a short syntax.
  • They automatically capture variables from the parent scope.
  • They are used for single-expression functions (i.e., no complex logic, only one expression).

2. Syntax of Arrow Functions

The syntax of an arrow function is much shorter than a regular anonymous function. Arrow functions use the fn keyword and a single expression. The result of the expression is implicitly returned.

Syntax:

fn(parameter_list) => expression;

Example (Simple Arrow Function):

<?php
// Arrow function with two parameters
$sum = fn($a, $b) => $a + $b;

// Using the arrow function
echo $sum(5, 3);  // Outputs: 8
?>
  • In this example, the arrow function $sum takes two parameters ($a and $b) and returns their sum. The result is printed when calling $sum(5, 3).

Example (Arrow Function Without Parameters):

<?php
// Arrow function without parameters
$getCurrentYear = fn() => date("Y");

// Using the arrow function
echo $getCurrentYear();  // Outputs: current year (e.g., 2024)
?>
  • This example demonstrates an arrow function without parameters. It returns the current year using the date(“Y”) function.

3. Using Arrow Functions with Arrays

Arrow functions are commonly used with array functions like array_map(), array_filter(), and array_reduce(). They make these operations more concise and readable.

Example (Using array_map() with Arrow Functions):

<?php
$numbers = [1, 2, 3, 4, 5];

// Multiply each number by 2 using array_map and an arrow function
$doubled = array_map(fn($n) => $n * 2, $numbers);

// Print the result
print_r($doubled);
?>

Output:

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
  • In this example, the arrow function fn($n) => $n * 2 is used to double each element in the $numbers array using array_map().

Example (Using array_filter() with Arrow Functions):

<?php
$numbers = [1, 2, 3, 4, 5, 6];

// Filter out even numbers using array_filter and an arrow function
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);

// Print the result
print_r($evens);
?>

Output:

Array
(
    [1] => 2
    [3] => 4
    [5] => 6
)
  • Here, the arrow function fn($n) => $n % 2 === 0 is used to filter out even numbers from the $numbers array using array_filter().

4. Capturing Variables from the Parent Scope

One of the most powerful features of arrow functions is that they automatically capture variables from the parent scope, without the need for the use keyword.

Example (Capturing Variables from Parent Scope):

<?php
$factor = 3;
$numbers = [1, 2, 3, 4, 5];

// Multiply each number by the $factor from the parent scope
$multiplied = array_map(fn($n) => $n * $factor, $numbers);

// Print the result
print_r($multiplied);
?>

Output:

Array
(
    [0] => 3
    [1] => 6
    [2] => 9
    [3] => 12
    [4] => 15
)
  • In this example, the arrow function fn($n) => $n * $factor captures the variable $factor from the parent scope. This allows the function to multiply each element in the $numbers array by the $factor without explicitly passing $factor as a parameter.

5. Differences Between Arrow Functions and Anonymous Functions

Although arrow functions are a type of anonymous function, they have some differences compared to traditional anonymous functions:

Feature Arrow Functions Anonymous Functions (Closures)
Syntax Uses the fn keyword and a single expression (=>). Uses the function keyword with a full function body.
Return Type Implicitly returns the result of the expression. Requires return statement to return values explicitly.
Variable Capture Automatically captures variables from the parent scope. Requires the use keyword to capture variables.
Scope Inherits scope from the parent (no need for use). Must explicitly pass variables using the use keyword.

Example (Anonymous Function vs. Arrow Function):

<?php
// Using an anonymous function (closure)
$factor = 2;
$anonymousFunction = function ($n) use ($factor) {
    return $n * $factor;
};
echo $anonymousFunction(5);  // Outputs: 10

// Using an arrow function
$arrowFunction = fn($n) => $n * $factor;
echo $arrowFunction(5);  // Outputs: 10
?>
  • In this example, the anonymous function requires the use ($factor) syntax to access the $factor variable from the parent scope, while the arrow function automatically captures the variable without needing use.

6. Example Use Case: Simplifying Array Operations

Let’s see a more complex example where we use arrow functions to simplify multiple array operations, such as filtering, mapping, and reducing data.

Example (Using Arrow Functions for Complex Array Operations):

<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Step 1: Filter even numbers
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);

// Step 2: Multiply each even number by 3
$multiplied = array_map(fn($n) => $n * 3, $evens);

// Step 3: Calculate the sum of the multiplied numbers
$sum = array_reduce($multiplied, fn($carry, $n) => $carry + $n, 0);

// Print results
echo "Even numbers: " . implode(", ", $evens) . "\n";
echo "Multiplied by 3: " . implode(", ", $multiplied) . "\n";
echo "Sum of multiplied numbers: $sum\n";
?>

Output:

Even numbers: 2, 4, 6, 8, 10
Multiplied by 3: 6, 12, 18, 24, 30
Sum of multiplied numbers: 90
  • In this example, we use three arrow functions to perform the following operations:
    • Filter even numbers from the $numbers array.
    • Multiply the filtered numbers by 3.
    • Calculate the sum of the multiplied numbers.

This demonstrates how arrow functions can be used to simplify and chain array operations.

Summary of PHP Arrow Functions:

Concept Description
Arrow Function Syntax Arrow functions use the fn keyword and a single expression syntax.
Automatic Variable Capture Arrow functions automatically capture variables from the parent scope.
Usage in Array Functions Arrow functions are often used in functions like array_map() and array_filter().
Difference from Anonymous Functions Arrow functions have a simpler syntax and implicit return compared to traditional anonymous functions.

Conclusion

Arrow functions in PHP provide a concise and readable way to write anonymous functions, especially for simple operations. In this tutorial, we covered:

  • The syntax of arrow functions and how they differ from traditional anonymous functions.
  • **Using arrow functions with arrays

**, such as in array_map(), array_filter(), and array_reduce().

  • Capturing variables from the parent scope automatically.
  • A practical use case that shows how arrow functions simplify complex array operations.

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples