πŸŽ‰ New: Top 75 PHP Interview Questions for 2026 β€” Free for all learners

Callback Functions – PHP

P
php Guru
Β· Β· 2 min read Β·

πŸ“Œ Key Takeaways

  • Callback Functions – PHP
  • Callback Functions
  • User Defined Functions callbacks.

Callback Functions

A callback function, which is often just called “callback,” is a function that is passed to another function as an argument.

A callback function can be any function that is already in use. To use a function as a callback function, you must pass the function’s name as an argument to another function:

Example

Give PHP’s array map() function a callback to figure out how long each string in an array is:

<!DOCTYPE html>
<html>
<body>

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

$colors = [“Red”, “Green”, “Blue”, “Black”];
$lengths = array_map(“my_callback”, $colors);
print_r($lengths);
?>

</body>
</html>

Output

Array ( [0] => 3 [1] => 5 [2] => 4 [3] => 5 )

Example 2

As of PHP version 7, anonymous functions can be passed as callback functions:

<!DOCTYPE html>
<html>
<body>

<?php
$colors = [“Red”, “Orange”, “Yellow”, “Pink”];
$lengths = array_map( function($item) { return strlen($item); } , $colors);
print_r($lengths);
?>

</body>
</html>

Output

Array ( [0] => 3 [1] => 6 [2] => 6 [3] => 4 )

 

User Defined Functions callbacks.

Callback functions can also be passed as arguments to user-defined functions and methods. To use callback functions inside a user-defined function or method, add parentheses around the variable and pass arguments as you would with regular functions:

Example

Use a user-defined function to run a callback:

<!DOCTYPE html>
<html>
<body>

<?php
function mark($var) {
return $var . “! “;
}

function ask($var) {
return $var . “? “;
}

function wordmark($var, $mark) {
// Calling the $mark callback function
echo $mark($var);
}

// Pass “mark” and “ask” as callback functions to wordmark()
wordmark(“Loream ipsum”, “mark”);
wordmark(“Loream ipsum”, “ask”);
?>

</body>
</html>

Output

"Callbacks

P
php Guru
PHP Developer & Technical Writer β€” phponline.in A seasoned PHP developer with 8+ years of experience in Laravel, MySQL, and REST APIs. Writes practical tutorials and career guides to help developers grow their skills and income. All salary data is researched from real job postings and developer surveys.
← Previous Post
Regular Expressions - PHP
Next Post β†’
PHP Exceptions