Skip to content

PHP Tutorial Functions

Arrow Functions

Lesson 112 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

An arrow function is a shorter way to write a simple anonymous function. It starts with fn and uses => to point to the result. Arrow functions arrived in PHP 7.4.

Compare the two styles for the same job:

index.php
PHP
<?php
$numbers = [1, 2, 3];

// anonymous function
$doubled = array_map(function (int $n): int {
    return $n * 2;
}, $numbers);

// arrow function
$doubled2 = array_map(fn(int $n): int => $n * 2, $numbers);

echo implode(", ", $doubled) . "\n";
echo implode(", ", $doubled2);
Output
OUTPUT
2, 4, 6
2, 4, 6

The arrow function has no { }, no return and no use. The result of the single expression is returned automatically.

Outside variables are captured automatically

A normal anonymous function needs use to see variables from outside. An arrow function sees them automatically, by value.

index.php
PHP
<?php
$taxRate = 0.18;
$prices = [100, 200];

$withTax = array_map(fn($price) => $price * (1 + $taxRate), $prices);

echo implode(", ", $withTax);
Output
OUTPUT
118, 236

Limits

  1. The body is one expression only. For several statements, use a normal anonymous function.
  2. Captured variables are copied. Changing them inside the function does not change the outside variable.
index.php
PHP
<?php
$count = 0;

$increase = fn() => $count++;
$increase();

echo $count;
Output
OUTPUT
0

Sorting with an arrow function

index.php
PHP
<?php
$users = [
    ["name" => "Zoya", "age" => 30],
    ["name" => "Ali", "age" => 22],
];

usort($users, fn($a, $b) => $a["age"] <=> $b["age"]);

echo $users[0]["name"];
Output
OUTPUT
Ali

Filtering

index.php
PHP
<?php
$words = ["php", "go", "javascript", "c"];

$long = array_filter($words, fn($w) => strlen($w) > 2);

echo implode(", ", $long);
Output
OUTPUT
php, javascript

Nesting

Arrow functions can contain another arrow function. The inner one also sees the outer variables.

index.php
PHP
<?php
$add = fn($x) => fn($y) => $x + $y;

echo $add(3)(4);
Output
OUTPUT
7
lightbulb
Use them for short callbacks
array_map, array_filter and usort with a single-line rule are the perfect home for fn. If it needs a second line, switch to a normal function.