WikiGalaxy

Personalize

PHP Callback Functions

Introduction to Callback Functions:

A callback function is a function that is passed as an argument to another function. This concept allows a function to call another function within it, enabling dynamic execution and enhancing flexibility in coding.


<?php
function my_callback($item) {
    return strtoupper($item);
}

$strings = ["apple", "banana", "cherry"];
$uppercaseStrings = array_map("my_callback", $strings);
print_r($uppercaseStrings);
?>
    

Console Output:

Array ( [0] => APPLE [1] => BANANA [2] => CHERRY )

Using Anonymous Functions as Callbacks

Anonymous Functions:

PHP allows the use of anonymous functions (closures) as callbacks. These are functions without a specified name and are often used when a callback is only needed once.


<?php
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($num) {
    return $num * $num;
}, $numbers);
print_r($squared);
?>
    

Console Output:

Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )

Callback Functions with User-Defined Functions

User-Defined Functions:

You can create user-defined functions to serve as callbacks, providing more control and customization over the operations performed by the callback.


<?php
function multiplyByTwo($num) {
    return $num * 2;
}

$values = [10, 20, 30];
$doubledValues = array_map("multiplyByTwo", $values);
print_r($doubledValues);
?>
    

Console Output:

Array ( [0] => 20 [1] => 40 [2] => 60 )

Callback Functions with Built-in Functions

Built-in Functions:

PHP's built-in functions can also be used as callbacks, providing a quick and efficient way to perform common operations.


<?php
$words = ["hello", "world"];
$capitalizedWords = array_map("ucfirst", $words);
print_r($capitalizedWords);
?>
    

Console Output:

Array ( [0] => Hello [1] => World )

Callback Functions with Object Methods

Object Methods:

In PHP, object methods can also be used as callbacks, allowing you to leverage object-oriented programming principles.


<?php
class MyClass {
    public function addPrefix($item) {
        return "prefix_" . $item;
    }
}

$obj = new MyClass();
$items = ["one", "two", "three"];
$prefixedItems = array_map([$obj, "addPrefix"], $items);
print_r($prefixedItems);
?>
    

Console Output:

Array ( [0] => prefix_one [1] => prefix_two [2] => prefix_three )

Callback Functions with Static Methods

Static Methods:

Static methods can also be used as callbacks, which can be particularly useful for utility functions that do not require an instance of the class.


<?php
class Utility {
    public static function multiply($a, $b) {
        return $a * $b;
    }
}

$result = array_map(["Utility", "multiply"], [1, 2, 3], [4, 5, 6]);
print_r($result);
?>
    

Console Output:

Array ( [0] => 4 [1] => 10 [2] => 18 )

Passing Parameters to Callback Functions

Parameters in Callbacks:

When using callbacks, you can pass additional parameters to the callback function, allowing for more dynamic and flexible code execution.


<?php
function appendSuffix($item, $suffix) {
    return $item . $suffix;
}

$words = ["car", "bike", "plane"];
$suffixedWords = array_map("appendSuffix", $words, array_fill(0, count($words), "_2023"));
print_r($suffixedWords);
?>
    

Console Output:

Array ( [0] => car_2023 [1] => bike_2023 [2] => plane_2023 )

Chaining Callback Functions

Chaining Callbacks:

Callbacks can be chained together to perform multiple operations in sequence, allowing for complex transformations and data processing tasks.


<?php
function trimString($item) {
    return trim($item);
}

function capitalizeString($item) {
    return ucfirst($item);
}

$rawStrings = [" hello ", " world ", " php "];
$processedStrings = array_map("capitalizeString", array_map("trimString", $rawStrings));
print_r($processedStrings);
?>
    

Console Output:

Array ( [0] => Hello [1] => World [2] => Php )

Callback Functions with Error Handling

Error Handling in Callbacks:

Implementing error handling in callback functions is crucial for robust applications, allowing you to gracefully manage unexpected situations.


<?php
function safeDivide($a, $b) {
    if ($b == 0) {
        return "Division by zero error!";
    }
    return $a / $b;
}

$results = array_map("safeDivide", [10, 20, 30], [2, 0, 5]);
print_r($results);
?>
    

Console Output:

Array ( [0] => 5 [1] => Division by zero error! [2] => 6 )

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025