Arrow Functions

A short syntax for small anonymous functions that return a value.

Syntax$fn = fn($x) => $x * 2;

Arrow functions (PHP 7.4+) provide a concise syntax for simple one-line functions. They automatically capture variables from the surrounding scope.

They are most useful with array functions like array_map() and array_filter().

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Pass a concise arrow function to array_map() to convert an array of price strings to floats.
  • Use an arrow function as the comparator in usort() to sort objects by a property without verbose syntax.
  • Capture an outer $taxRate variable automatically in an arrow function passed to array_map().

More examples

Arrow function with array_map

fn() => ... is a one-expression function; the return is implicit, making array_map callbacks very concise.

Example · php
<?php
$prices = ['9.99', '4.49', '14.00'];
$floats = array_map(fn($p) => (float) $p, $prices);

print_r($floats); // [9.99, 4.49, 14.0]

Auto-capturing outer variables

Unlike regular closures, arrow functions capture outer scope variables by value automatically without use().

Example · php
<?php
$taxRate = 0.1;

$prices    = [10.0, 25.0, 50.0];
$withTax   = array_map(fn($p) => $p * (1 + $taxRate), $prices);

print_r($withTax); // [11.0, 27.5, 55.0]

Arrow function in usort

An arrow function as a usort comparator replaces a multi-line closure with a single readable expression.

Example · php
<?php
$products = [
    ['name' => 'Widget', 'price' => 9.99],
    ['name' => 'Gadget', 'price' => 4.49],
];

usort($products, fn($a, $b) => $a['price'] <=> $b['price']);

foreach ($products as $p) {
    echo "{$p['name']}: {$p['price']}\n";
}

Discussion

  • Be the first to comment on this lesson.