PHP Callback Functions are functions that can be passed as arguments to other functions or used as return values from functions. Here are some examples of how to use PHP’s callback function functionality:
- Using a callback function with
array_map()
:
function square($n) {
return $n * $n;
}
$numbers = array(1, 2, 3, 4, 5);
$squares = array_map('square', $numbers);
print_r($squares);
In this example, the square()
function is defined to calculate the square of a number. The array_map()
function is used to apply the square()
function to each element of the $numbers
array and store the results in a new array called $squares
.
- Using a callback function with
usort()
:
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$numbers = array(4, 2, 8, 6, 7, 3, 1, 5);
usort($numbers, 'cmp');
print_r($numbers);
In this example, the cmp()
function is defined to compare two values and return -1, 0, or 1 depending on their relative order. The usort()
function is used to sort the $numbers
array using the cmp()
function as the comparison function.
- Using a callback function with
array_filter()
:
function odd($n) {
return ($n % 2 == 1);
}
$numbers = array(1, 2, 3, 4, 5);
$odds = array_filter($numbers, 'odd');
print_r($odds);
In this example, the odd()
function is defined to return true
if a number is odd and false
otherwise. The array_filter()
function is used to filter the $numbers
array and keep only the odd numbers, which are stored in a new array called $odds
.
Callback functions can be used for a variety of purposes, such as sorting arrays, filtering arrays, and transforming data. By using callback functions, developers can create more flexible and reusable code that can be customized to fit different use cases.