PHP
Arrow functions (fn)
Learn to write short arrow functions with automatic variable capture using fn =>.
Arrow functions: fn() =>
Since PHP 7.4 you can define an arrow function with fn($x) => $x * 2. It is the short form of an anonymous function.
Two big differences: first, it returns a single expression (no return keyword, it returns automatically). Second, it captures outer variables automatically; no use needed.
For example $tax = 0.2; $f = fn($p) => $p * (1 + $tax); — $tax flows in by itself.
When to use an arrow function?
Arrow functions are ideal for short single-expression returns. The form fn($n) => $n * 2 is much shorter than function ($n) { return $n * 2; }.
You do not need to write use by hand; arrow functions auto-capture. This keeps long closures readable.
But when you need multiple statements (assignment, if, loop), you must use a classic function. Arrow functions return a single value only.
Exercise Compute squares with array_map
Compute the square of each element in [1, 2, 3] with array_map; use the fn($n) => $n * $n arrow function. Then print each square on a new line.
Show example solution
Write $squares = array_map(fn($n) => $n * $n, [1, 2, 3]);. Then foreach ($squares as $s) { echo $s . "\n"; }.
Example solution:
<?php
// Compute squares with array_map and fn
$squares = array_map(fn($n) => $n * $n, [1, 2, 3]);
foreach ($squares as $s) {
echo $s . "\n";
}
Test yourself
-
Arrow function vs closure
- fn($x) => ...
- Arrow function
- function ($x) { ... }
- Anonymous function
- use ($x)
- Manual capture into closure
- auto capture
- Arrow function trait
-
Which statement about arrow functions is true?
- Manual capture with use is required
- It can contain multiple statements
- It auto-captures outer scope variables
- It can only return a number
Show answer
It auto-captures outer scope variables — Correct. Arrow functions auto-capture outer scope variables without use.
-
Complete the arrow function definition
<?php
$tax = 0.2;
$addTax = ____ ($price) => $price * (1 + $tax);
echo $addTax(100) . "\n";
Show answer
<?php
$tax = 0.2;
$addTax = fn ($price) => $price * (1 + $tax);
echo $addTax(100) . "\n";
Next lesson: The callable type