Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

Anonymous, Callback and Arrow Functions

Anonymous Functions 15 minFunctions are values in PHP, so an anonymous function or a short arrow function can be passed as a callback to helpers such as array_map and array_filter, which call it for each item.

php / Anonymous, Callback and Arrow Functions

Explore each scene at your own pace.

01 · The rule

The rule

Anonymous, Callback and Arrow Functions

Functions are values in PHP, so an anonymous function or a short arrow function can be passed as a callback to helpers such as array_map and array_filter, which call it for each item.

Pass behavior as a value and inspect what the function captures from its surroundings.

Pageturn wants each price doubled for a two-copy bundle, and only books under 10 shown in a "bargains" box. PHP's array_map and array_filter do the looping for you, but they need to be told what to do with each item. You tell them by handing over a function as a value.

The rule

A function can be a value: pass it in, and it gets called back.

A callback is a function you pass to another function, which calls it for you:

<?php
$prices = [9.99, 7.50, 12.00];

$doubled  = array_map(fn($p) => $p * 2, $prices);     // [19.98, 15, 24]
$bargains = array_filter($prices, fn($p) => $p < 10);  // [9.99, 7.5]

Note the argument order: array_map(callback, array) but array_filter(array, callback). It is a well-known PHP inconsistency, so check it every time.

There are three ways to write the function you pass:

1. An anonymous function (closure) has no name and is stored or passed directly. To use a variable from outside, list it with use. It is copied at the moment the closure is created:

$rate = 0.9;
$sale = function (float $p) use ($rate) {
    return $p * $rate;
};
echo $sale(10);   // 9

2. An arrow function (PHP 7.4) is the short form for a single expression: fn($p) => $p * $rate. It captures outside variables automatically, also by value, and returns the expression without a return keyword. It cannot contain multiple statements.

3. A named function as a string, such as array_map('strtoupper', $titles), uses an existing function as the callback.

Without use, a normal anonymous function cannot see $rate; it follows the same scope rule as any function.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.