TExcelTAD
Home › PHP › PHP Callback Functions

PHP Callback Functions

A callback is a function that you hand to another function, so that it can call it later. Instead of writing a new loop every time you want to transform, filter or sort an array, you write only the small piece that differs — "double this number", "keep this item if it's in stock" — and pass it as a callback to a general-purpose function such as array_map() or usort().

What can be a callback?

PHP calls anything that can be used as a callback a callable. There are several forms:

Form Example
Name of a function, as a string 'strtoupper'
Anonymous function (closure) function ($x) { return $x * 2; }
Arrow function fn($x) => $x * 2
Object method [$cart, 'addItem']
Static method [Formatter::class, 'money'] or 'Formatter::money'
First-class callable syntax strtoupper(...), $cart->addItem(...)

You can call any callable stored in a variable with $fn(...), or with call_user_func($fn, ...), and check one with is_callable().

php · try it yourself
<?php
function shout(string $text): string
{
    return strtoupper($text) . '!';
}

$byName  = 'shout';
$closure = function (string $text): string { return "<$text>"; };
$arrow   = fn(string $text): string => str_repeat($text, 2);

echo $byName('hi') . PHP_EOL;
echo $closure('hi') . PHP_EOL;
echo $arrow('hi') . PHP_EOL;
echo call_user_func('ucfirst', 'php') . PHP_EOL;

var_dump(is_callable('shout'), is_callable('no_such_function'));
HI!
<hi>
hihi
Php
bool(true)
bool(false)

Callbacks with array functions

The built-in array functions are where callbacks shine:

php · try it yourself
<?php
$prices = ['tea' => 3.5, 'coffee' => 7.25, 'cake' => 12.0, 'water' => 1.0];

// array_map: transform every value
$withTax = array_map(fn($p) => round($p * 1.1, 2), $prices);
print_r($withTax);

// array_filter: keep values for which the callback returns true
$cheap = array_filter($prices, fn($p) => $p < 5);
echo "Cheap: " . implode(', ', array_keys($cheap)) . PHP_EOL;

// array_reduce: combine all values into one
$total = array_reduce($prices, fn($carry, $p) => $carry + $p, 0);
echo "Total: $total" . PHP_EOL;

// usort / uasort: custom sorting (spaceship operator returns -1, 0 or 1)
uasort($prices, fn($a, $b) => $b <=> $a);
echo "Most expensive first: " . implode(', ', array_keys($prices)) . PHP_EOL;
Array
(
    [tea] => 3.85
    [coffee] => 7.98
    [cake] => 13.2
    [water] => 1.1
)
Cheap: tea, water
Total: 23.75
Most expensive first: cake, coffee, tea, water

Writing your own function that takes a callback

Type the parameter as callable (or Closure) and call it like a function. This makes your function reusable for many situations:

php · try it yourself
<?php
function retry(int $times, callable $task): string
{
    for ($attempt = 1; $attempt <= $times; $attempt++) {
        $result = $task($attempt);
        if ($result !== null) {
            return "succeeded on attempt $attempt: $result";
        }
        echo "attempt $attempt failed" . PHP_EOL;
    }
    return "gave up after $times attempts";
}

// A fake network call that only works on the third try
echo retry(5, fn(int $n) => $n >= 3 ? 'data loaded' : null) . PHP_EOL;
echo retry(2, fn(int $n) => null) . PHP_EOL;
attempt 1 failed
attempt 2 failed
succeeded on attempt 3: data loaded
attempt 1 failed
attempt 2 failed
gave up after 2 attempts

Closures and captured variables

An anonymous function cannot see variables from the surrounding code unless you list them in a use clause. Values are copied when the closure is created; use & to capture by reference. Arrow functions (fn) capture outer variables automatically, by value.

php · try it yourself
<?php
$rate = 0.2;
$discount = function (float $price) use ($rate): float {
    return $price * (1 - $rate);
};
$rate = 0.5;  // too late: the closure captured 0.2
echo $discount(100) . PHP_EOL;

$count = 0;
$counter = function () use (&$count): void { $count++; };
$counter();
$counter();
echo "count = $count" . PHP_EOL;

$min = 10;
$big = array_filter([4, 12, 9, 30], fn($n) => $n > $min);  // $min captured automatically
echo implode(' ', $big) . PHP_EOL;

// A function that returns a configured callback
function multiplier(int $factor): Closure
{
    return fn(int $x): int => $x * $factor;
}
$triple = multiplier(3);
echo implode(' ', array_map($triple, [1, 2, 3])) . PHP_EOL;
80
count = 2
12 30
3 6 9

Methods as callbacks

Pass an object method as [$object, 'method'], or more readably with the first-class callable syntax $object->method(...):

php · try it yourself
<?php
class Slugger
{
    public function slug(string $title): string
    {
        return strtolower(trim(preg_replace('/[^A-Za-z0-9]+/', '-', $title), '-'));
    }
}

$s = new Slugger();
$titles = ['Hello World', 'PHP 8.4 is here!', '  Callbacks & You '];

print_r(array_map([$s, 'slug'], $titles));
print_r(array_map($s->slug(...), ['First-class Callables']));
Array
(
    [0] => hello-world
    [1] => php-8-4-is-here
    [2] => callbacks-you
)
Array
(
    [0] => first-class-callables
)

Tip: Arrow functions are perfect for one-line callbacks. Use a full function (or a named function) when the logic needs several statements.

Test yourself

Which of these is NOT a valid callable?

  1. 'strlen'
  2. fn($x) => $x + 1
  3. [$obj, 'save']
  4. '$obj->save'

What does array_filter([1, 6, 3, 8], fn($n) => $n > 4) keep?

  1. [1, 3]
  2. [6, 8] with keys 1 and 3
  3. [6, 8] with keys 0 and 1
  4. true

How does an anonymous function access a variable from the surrounding scope?

  1. Automatically
  2. With the global keyword only
  3. With a use ($var) clause
  4. It cannot