What is anonymous function in PHP? Explain with an example.

Anonymous function

PHP allows the functions without any specified name are known as anonymous function. These anonymous functions are very useful as the callback parameters.

Example

$sourceArr = range(1, 5);
$squareArr = array_map(function($value) { return $value * $value; }, $sourceArr);
print_r($sourceArr);
print_r($squareArr);

Output

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

Explanation

In the above example the array_map function used an anonymous function as the callback parameters. The anonymous function takes every element of the sourceArr and multiply with itself and then stores it in the same index of a new variable. At the end it returns the new value of the new variable.

Comments