PHP Callback Functions
In this page:
What Is a Callback?
A callback is any value PHP can call as a function when passed into another function -- a string naming a function, a closure, or an array pairing an object with a method name. Callbacks let you hand custom behavior into generic array/sorting functions without them needing to know your logic in advance.
Example: What Is a Callback?
<?php
$numbers = [1, 2, 3];
$result = array_map("strval", $numbers);
print_r($result);
?>
Login to try C/C++/Java/PHP code in the editor
Passing a Function Name
The simplest callback is just the function's name as a string, like "strtoupper" passed to array_map(). PHP looks up that name at call time and invokes it, which works for both built-in and user-defined functions, but offers no type-checking until the call actually happens.
Example: Passing a Function Name
<?php
$words = ["hello", "world"];
print_r(array_map("strtoupper", $words));
?>
Login to try C/C++/Java/PHP code in the editor
Passing a Closure
An anonymous function (function($x) { ... }) or arrow function (fn($x) => ...) defined inline is the most common modern callback style, since it lets you write the logic right where it's used instead of naming a separate function elsewhere. Closures can also capture outer variables via use(), which named functions can't do.
Example: Passing a Closure
<?php
$numbers = [1, 2, 3];
$doubled = array_map(function ($n) { return $n * 2; }, $numbers);
print_r($doubled);
?>
Login to try C/C++/Java/PHP code in the editor
Passing a Method Callback
To use an object's method as a callback, pass a two-element array: [$object, methodName] for an instance method, or [ClassName, methodName] for a static one. This is how you plug object behavior into functions like usort() without writing a wrapper closure.
Example: Passing a Method Callback
<?php
class Formatter {
function upper($s) { return strtoupper($s); }
}
$formatter = new Formatter();
$result = array_map([$formatter, 'upper'], ["hello", "world"]);
print_r($result);
?>
Login to try C/C++/Java/PHP code in the editor
Common Callback Consumers
array_map() applies a callback to every element and returns a new array, array_filter() keeps only elements the callback returns true for, and usort() uses a callback that returns negative/zero/positive to define a custom sort order. All three expect the exact same callback formats covered above.
Example: Common Callback Consumers
<?php
$numbers = [1, 2, 3, 4];
print_r(array_map(fn($n) => $n * 2, $numbers));
print_r(array_filter($numbers, fn($n) => $n % 2 === 0));
usort($numbers, fn($a, $b) => $b <=> $a);
print_r($numbers);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: