← Back to PHP Course | Chapter 5: Functions | Lesson 8 of 10

PHP Arrow Functions

What are Arrow Functions? (PHP 7.4+)

Introduced in PHP 7.4, arrow functions use the fn keyword and are limited to a single expression, whose result is returned automatically — there's no explicit return keyword, and no curly-brace body, which is what makes them so much shorter than a standard anonymous function for simple cases.

Example: What are Arrow Functions? (PHP 7.4+)

php
<?php
$double = fn($x) => $x * 2;
echo $double(5);
?>

Implicit Value Binding

Unlike a regular anonymous function, an arrow function automatically captures any variable from its surrounding scope that it actually references — by value — with no use clause needed. This implicit capture is the main practical difference from a standard closure.

Example: Implicit Value Binding

php
<?php
$tax = 0.1;
$addTax = fn($price) => $price + ($price * $tax);
echo $addTax(100);
?>

Arrow Functions as Callbacks

Because arrow functions are so compact, they read naturally as an inline argument to something like array_map() or usort() — the entire callback fits on the same line as the function call that needs it, without a separate multi-line closure definition above.

Example: Arrow Functions as Callbacks

php
<?php
$numbers = [1, 2, 3, 4];
$doubled = array_map(fn($n) => $n * 2, $numbers);
print_r($doubled);
?>

Typing Arrow Functions

You can add parameter and return type declarations to an arrow function exactly as you would to any other function — fn(int $x): int => $x * 2 — so the brevity of the syntax doesn't come at the cost of giving up type safety.

Example: Typing Arrow Functions

php
<?php
$double = fn(int $x): int => $x * 2;
echo $double(5);
?>

Arrow Functions vs Anonymous Functions

The tradeoff for an arrow function's compactness is that it can only contain a single expression — no loops, no multiple statements, no intermediate variables. Anything beyond that single expression requires falling back to a standard anonymous function instead.

Example: Arrow Functions vs Anonymous Functions

php
<?php
$sum = fn($a, $b) => $a + $b;
echo $sum(2, 3);
// A multi-statement version would need a regular function instead
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.