-
Hajipur, Bihar, 844101
In PHP, a callback function is a function that is passed as an argument to another function. This allows the receiving function to call the passed function dynamically at runtime.
Callbacks are useful for customizing behavior, processing arrays, or executing code dynamically based on user requirements.
A callback function is essentially a reference to a function. Instead of executing a function immediately, you can pass it to another function, which can then decide when and how to run it.
Use cases:
Sorting arrays using custom comparison logic.
Applying transformations to each element of an array.
Implementing flexible and reusable code.
Named functions – Traditional functions defined using function
.
Anonymous functions – Functions without names, also called closures.
Static methods – Class methods used as callbacks.
Object methods – Non-static methods passed as callbacks.
<?php
// Function that takes a callback
function greetUser($callback) {
echo $callback("Vicky"); // Call the passed function
}
// Named function to pass as callback
function sayHello($name) {
return "Hello, $name!";
}
// Using the callback
greetUser("sayHello");
?>
Output:
Hello, Vicky!
Explanation:
The sayHello
function is passed as an argument to greetUser
.
Inside greetUser
, the function is called using $callback("Vicky")
.
<?php
// Function accepting a callback
function processName($callback) {
echo $callback("Sanjana");
}
// Using an anonymous function as a callback
processName(function($name) {
return "Welcome, $name!";
});
?>
Output:
Welcome, Sanjana!
Explanation:
Anonymous functions can be defined inline without a name.
Useful for short, one-time tasks without cluttering the code with separate functions.
array_map
with CallbackThe array_map
function applies a callback to every element of an array.
<?php
$numbers = [1, 2, 3, 4, 5];
// Callback function to double a number
function double($num) {
return $num * 2;
}
// Apply callback to each element
$doubledNumbers = array_map("double", $numbers);
print_r($doubledNumbers);
?>
Output:
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
Explanation:
array_map
takes the callback double
and applies it to each element.
Returns a new array with modified values.
You can also use anonymous functions with array_map
:
$doubledNumbers = array_map(function($num) {
return $num * 2;
}, $numbers);
usort
with CallbackThe usort
function sorts an array using a custom comparison function.
<?php
$fruits = ["apple", "banana", "cherry", "date"];
// Callback function to sort by string length
function sortByLength($a, $b) {
return strlen($a) - strlen($b);
}
// Sort the array
usort($fruits, "sortByLength");
print_r($fruits);
?>
Output:
Array ( [0] => date [1] => apple [2] => banana [3] => cherry )
Explanation:
usort
calls the callback sortByLength
for each pair of elements.
Sorting logic is customizable via the callback.
You can also use object methods as callbacks.
<?php
class Greeter {
public function greet($name) {
return "Hello, $name!";
}
}
$greeter = new Greeter();
// Passing object method as callback
function welcomeUser($callback) {
echo call_user_func($callback, "Amit");
}
// Using array notation for object method
welcomeUser([$greeter, "greet"]);
?>
Output:
Hello, Amit!
Explanation:
Object methods are passed as arrays: [object, "methodName"]
.
call_user_func
executes the callback dynamically.
<?php
class MathOperations {
public static function square($num) {
return $num * $num;
}
}
$numbers = [1, 2, 3, 4];
// Using static method as callback
$squaredNumbers = array_map(["MathOperations", "square"], $numbers);
print_r($squaredNumbers);
?>
Output:
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
Explanation:
Static methods can be referenced with class name and method name.
Combined with array_map
, they allow efficient array transformations.
Flexibility: Change behavior dynamically without modifying the main function.
Reusability: Functions can work with different callbacks for different tasks.
Cleaner code: Avoid repetitive loops or conditionals.
Integration with built-in functions: Many PHP array functions rely on callbacks (array_map
, array_filter
, usort
, etc.).
Filtering arrays dynamically using array_filter
.
Sorting data using usort
or uasort
.
Applying transformations to API data or JSON arrays.
Event handling in custom frameworks.
Middleware logic in PHP-based applications.
array_map
→ Apply a callback to each array element.
array_filter
→ Keep elements based on a callback condition.
usort
→ Custom sorting logic.
uasort
→ Sort associative arrays with a callback.
call_user_func
→ Call a function dynamically.
call_user_func_array
→ Call a function with multiple parameters.
Prefer anonymous functions for simple, one-time callbacks.
Use named functions for reusable logic.
Ensure callbacks are callable before passing (is_callable()
can help).
Keep callbacks lightweight to avoid performance issues in loops.
Combine callbacks with array functions for cleaner, functional-style code.
Callback functions are functions passed as arguments to other functions.
They provide flexibility, reusability, and dynamic execution.
PHP supports named functions, anonymous functions, object methods, and static methods as callbacks.
Many built-in functions like array_map
, array_filter
, and usort
rely on callbacks.
Mastering callbacks helps create modular, efficient, and dynamic PHP applications.
Write a PHP named function that takes a number and returns its square, then pass it as a callback to array_map
for an array of numbers.
Create a PHP anonymous function as a callback to convert all strings in an array to uppercase using array_map
.
Write a PHP function that filters an array of numbers to keep only even numbers using array_filter
and a callback.
Create a PHP callback function to sort an array of strings by length using usort
.
Write a PHP class with a static method that doubles a number, then use it as a callback in array_map
.
Create a PHP object method that greets a user, and call it dynamically using call_user_func
.
Write a PHP anonymous function as a callback that adds 10 to each element of an array using array_map
.
Create a PHP callback function that checks if a string starts with a specific letter, and use it with array_filter
.
Write a PHP function that takes another function as a parameter and applies it to a number to return the result.
Create a PHP callback that calculates the factorial of a number and use it to process an array of integers.