Saturday, September 6, 2025
HomeLanguagesPHP Arrow Functions

PHP Arrow Functions

Arrow functions, also known as “short closures”, is a new feature introduced in PHP 7.4 that provides a more concise syntax for defining anonymous functions. Arrow functions allow you to define a function in a single line of code, making your code more readable and easier to maintain.

Syntax:

$fn = $fun(x) => some_operations

Example 1: In this example, we will declare an array and use the array_reduce() method and arrow function to find the sum of array elements.

PHP




<?php
   
// Declare an array
$arr = [1, 2, 3, 4, 5, 6, 7];
  
$sum = array_reduce($arr, fn($carry, $item) => $carry + $item);
  
echo $sum;
?>


Output:

28

Example 2: In this example, we will declare an array and use the array_map() function to display array elements in multiple of 2.

PHP




<?php
   
$arr = [1, 2, 3, 4, 5, 6, 7];
$res = array_map(fn($n) => $n * 2, $arr);
print_r($res);
?>


Output:

Array
( 
       [0] => 2 
       [1] => 4 
       [2] => 6 
       [3] => 8 
       [4] => 10 
       [5] => 12 
       [6] => 14 
)

Reference: https://www.php.net/manual/en/functions.arrow.php

RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS