PHP Callback Functions

Passing functions as arguments for flexible code

🔄 What are Callback Functions?

Callback functions are functions passed as arguments to other functions. They enable flexible, reusable code by allowing you to customize behavior dynamically. Callbacks are essential for array operations, event handling, and asynchronous programming.


<?php
// Simple callback example
function greet($name, $callback) {
    $message = "Hello, $name!";
    return $callback($message);
}

$result = greet("John", function($msg) {
    return strtoupper($msg);
});

echo $result; // Output: HELLO, JOHN!
?>
                                    

Output:

HELLO, JOHN!

Types of Callbacks

📝

Named Functions

Pass regular function names as strings to use them as callbacks in other functions.

<?php
function double($n) {
    return $n * 2;
}
$result = array_map("double", [1, 2, 3]);
// [2, 4, 6]
?>

Anonymous Functions

Create inline functions without names for one-time use as callbacks, also called closures.

<?php
$result = array_map(
    function($n) {
        return $n * 2;
    }, 
    [1, 2, 3]
);
?>
➡️

Arrow Functions

Short syntax for simple callbacks introduced in PHP 7.4, perfect for one-line operations.

<?php
$result = array_map(
    fn($n) => $n * 2,
    [1, 2, 3]
);
// [2, 4, 6]
?>
🎯

Callable Type

Use the callable type hint to ensure parameters are valid functions that can be called.

<?php
function execute(callable $callback) {
    return $callback();
}
execute(fn() => "Done!");
?>

🔹 Using Named Functions as Callbacks

Pass function names as strings to use them as callbacks:

<?php
// Define a function
function square($number) {
    return $number * $number;
}

// Use it as a callback with array_map
$numbers = [1, 2, 3, 4, 5];
$squared = array_map("square", $numbers);

echo "Original: " . implode(", ", $numbers) . "<br>";
echo "Squared: " . implode(", ", $squared);
?>

Output:

Original: 1, 2, 3, 4, 5
Squared: 1, 4, 9, 16, 25

🔹 Anonymous Functions (Closures)

Create functions on-the-fly without naming them:

<?php
$numbers = [1, 2, 3, 4, 5];

// Filter even numbers using anonymous function
$evens = array_filter($numbers, function($n) {
    return $n % 2 == 0;
});

echo "All numbers: " . implode(", ", $numbers) . "<br>";
echo "Even numbers: " . implode(", ", $evens);
?>

Output:

All numbers: 1, 2, 3, 4, 5
Even numbers: 2, 4

🔹 Arrow Functions (PHP 7.4+)

Shorter syntax for simple callbacks:

<?php
$prices = [10, 20, 30, 40];

// Add tax using arrow function
$withTax = array_map(fn($price) => $price * 1.1, $prices);

echo "Original prices: $" . implode(", $", $prices) . "<br>";
echo "With 10% tax: $" . implode(", $", $withTax);
?>

Output:

Original prices: $10, $20, $30, $40
With 10% tax: $11, $22, $33, $44

🔹 Custom Functions with Callbacks

Create your own functions that accept callbacks:

<?php
// Function that accepts a callback
function processArray($array, $callback) {
    $result = [];
    foreach ($array as $item) {
        $result[] = $callback($item);
    }
    return $result;
}

// Use with different callbacks
$numbers = [1, 2, 3];

$doubled = processArray($numbers, fn($n) => $n * 2);
$tripled = processArray($numbers, fn($n) => $n * 3);

echo "Doubled: " . implode(", ", $doubled) . "<br>";
echo "Tripled: " . implode(", ", $tripled);
?>

Output:

Doubled: 2, 4, 6
Tripled: 3, 6, 9

🔹 Using Callbacks with array_filter()

Filter array elements based on custom conditions:

<?php
$products = [
    ["name" => "Laptop", "price" => 1000],
    ["name" => "Mouse", "price" => 25],
    ["name" => "Keyboard", "price" => 75],
    ["name" => "Monitor", "price" => 300]
];

// Filter products over $50
$expensive = array_filter($products, function($product) {
    return $product["price"] > 50;
});

echo "Expensive products:<br>";
foreach ($expensive as $product) {
    echo "- {$product['name']}: \${$product['price']}<br>";
}
?>

Output:

Expensive products:
- Laptop: $1000
- Keyboard: $75
- Monitor: $300

🔹 Using Callbacks with array_reduce()

Reduce an array to a single value using a callback:

<?php
$numbers = [1, 2, 3, 4, 5];

// Calculate sum
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);

// Calculate product
$product = array_reduce($numbers, fn($carry, $item) => $carry * $item, 1);

echo "Numbers: " . implode(", ", $numbers) . "<br>";
echo "Sum: $sum<br>";
echo "Product: $product";
?>

Output:

Numbers: 1, 2, 3, 4, 5
Sum: 15
Product: 120

🔹 Callbacks with usort()

Sort arrays with custom comparison logic:

<?php
$students = [
    ["name" => "Alice", "score" => 85],
    ["name" => "Bob", "score" => 92],
    ["name" => "Charlie", "score" => 78]
];

// Sort by score (descending)
usort($students, function($a, $b) {
    return $b["score"] - $a["score"];
});

echo "Students sorted by score:<br>";
foreach ($students as $student) {
    echo "{$student['name']}: {$student['score']}<br>";
}
?>

Output:

Students sorted by score:
Bob: 92
Alice: 85
Charlie: 78

🔹 Common Array Functions with Callbacks

Popular Callback Functions:

  • array_map() - Apply callback to each element, return new array
  • array_filter() - Filter elements based on callback condition
  • array_reduce() - Reduce array to single value using callback
  • array_walk() - Apply callback to each element (modifies original)
  • usort() - Sort array using custom comparison callback
  • uasort() - Sort associative array maintaining key association
  • array_walk_recursive() - Apply callback to nested arrays

🧠 Test Your Knowledge

What is the short syntax for callbacks introduced in PHP 7.4?