iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Arrow Functions

Arrow functions (PHP 7.4+) are concise one-expression anonymous functions that automatically capture outer-scope variables.

The shape

PHP
$square = fn($x) => $x * $x;
echo $square(5);          // 25

That's equivalent to:

PHP
$square = function ($x) {
    return $x * $x;
};

Automatic capture

Classic closures need use () to import outer variables. Arrow functions don't — they read whatever's in scope:

PHP
$multiplier = 3;

// Old way
$triple = function ($x) use ($multiplier) {
    return $x * $multiplier;
};

// Arrow way
$triple = fn($x) => $x * $multiplier;

echo $triple(7);   // 21

Where they shine

PHP
$nums = [1, 2, 3, 4];

$doubled = array_map(fn($n) => $n * 2, $nums);
$evens   = array_filter($nums, fn($n) => $n % 2 === 0);
$total   = array_reduce($nums, fn($c, $n) => $c + $n, 0);

usort($users, fn($a, $b) => $a->age <=> $b->age);   // sort by age

Limits

  • Single expression only — no statements, no return keyword.
  • Can't have multiple lines.
  • Type declarations and return types still work.
Tip: If your callback needs more than one expression, use a regular function () { … } closure — readability beats brevity.

Example

Example
<?php
$square = fn($x) => $x * $x;
echo $square(5), PHP_EOL;

$nums = [1, 2, 3, 4];
print_r(array_map(fn($n) => $n * 2, $nums));
Try it Yourself »

Exercise

Arrow function keyword.

$sq = ($x) => $x * $x;

Test yourself

Q1. Arrow functions arrived in…
Q2. Arrow functions capture outer variables…
Q3. fn allows…

Discussion

Loading…