PHP Callback Functions

PHP Callback Functions

A callback function (often just called a "callback") is a function which is passed as an argument into another function.

Any existing function can be used as a callback function. To pass a function as an argument, you simply pass its name as a string.


1. Using Callbacks with array_map()

The array_map() function is a perfect example of a built-in PHP function that uses callbacks. It takes a callback function and an array, and applies that callback function to every single item in the array!

Let's create a custom callback function that measures the length of strings, and map it across an array of fruits.

Callback Example

<?php
// Our custom callback function
function my_callback($item) {
  return strlen($item);
}

$strings = ["apple", "orange", "banana", "coconut"];

// Pass "my_callback" as a string into array_map $lengths = array_map("my_callback", $strings);

print_r($lengths); ?>

Notice how we only passed the name "my_callback" without parentheses (). The array_map function takes care of executing it!


2. Anonymous Callback Functions

Starting with PHP 7, you can pass anonymous functions (closures) directly as callbacks, meaning you don't even have to name them! This makes the code much shorter and keeps things contained.

Anonymous Callback Example

<?php
$strings = ["apple", "orange", "banana", "coconut"];

// Writing the function directly inside array_map $lengths = array_map( function($item) { return strlen($item); } , $strings);

print_r($lengths); ?>

Exercise

?

How do you typically pass an existing named function as a callback argument in PHP?