Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:
$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return
arr_square = array_map(function($val) { return
val; }, $arr);
Otherwise you would need to define a function that you possibly only use once:
function isEven($val) { return
arr_even = array_filter($arr, 'isEven');
function square($val) { return
val; }
$arr_square = array_map('square', $arr);
Answer from Gumbo on Stack OverflowWhy and how do you use anonymous functions in PHP? - Stack Overflow
php - Why use anonymous function? - Stack Overflow
Why would I ever use an anonymous function stored in a variable when I can use a normal function instead?
Passing parameter to Usort?
How do you declare and use an anonymous function in PHP?
function keyword and assign it to a variable.
Example:
$sum = function($a, $b) { return $a + $b; };
echo $sum(5, 3);
You can also pass it as a callback in array functions.What is an anonymous function?
$greet = function($name) { return "Hello, " . $name; };
echo $greet("World");
What is the difference between anonymous functions and arrow functions in PHP?
fn keyword and automatically capture variables from the parent scope.
They are limited to a single expression. Example:
$factor = 2;
$multiply = fn($x) => $x * $factor;
echo $multiply(5); Videos
Anonymous functions are useful when using functions that require a callback function like array_filter or array_map do:
$arr = range(0, 10);
$arr_even = array_filter($arr, function($val) { return
arr_square = array_map(function($val) { return
val; }, $arr);
Otherwise you would need to define a function that you possibly only use once:
function isEven($val) { return
arr_even = array_filter($arr, 'isEven');
function square($val) { return
val; }
$arr_square = array_map('square', $arr);
Anonymous functions are available from PHP 5.3.
Anonymous functions have been available in PHP for a long time: create_function has been around since PHP 4.0.1. However you're quite right that there is a new concept and syntax available as of PHP 5.3.
Should I use them or avoid them? If so, how?
If you've ever used create_function before, then the new syntax can simply slip right in where you used that. As other answers have mentioned, a common case is for 'throwaway' functions where they are to be used just once (or in a single place at least). Commonly that comes in the form of callbacks for the likes of array_map/reduce/filter, preg_replace_callback, usort, etc..
Example of using anonymous functions to count the number of times letters appear in words (this could be done in a number of other ways, it is just an example):
$array = array('apple', 'banana', 'cherry', 'damson');
// For each item in the array, count the letters in the word
$array = array_map(function($value){
$letters = str_split($value);
$counts = array_count_values($letters);
return $counts;
}, $array);
// Sum the counts for each letter
$array = array_reduce($array, function($reduced, $value) {
foreach ($value as $letter => $count) {
if ( ! isset($reduced[$letter])) {
$reduced[$letter] = 0;
}
$reduced[$letter] += $count;
}
return $reduced;
});
// Sort counts in descending order, no anonymous function here :-)
arsort($array);
print_r($array);
Which gives (snipped for brevity):
Array
(
[a] => 5
[n] => 3
[e] => 2
... more ...
[y] => 1
)
I would say that anonymous functions show their beauty when there is good library classes/functions that use them. They are not that sexy by themselves. In the world of .net there is technology called LINQ that makes huge use of then in very idiomatic manner. Now back to PHP.
First example, sort:
uasort($array, function(
b) { return(
b); });
You can specify complex logic for sorting:
uasort($array, function(
b) { return(
b->Age); });
Another example:
$data = array(
array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'),
array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'),
array('id' => 3, 'name' => 'James', 'position' => 'Director')
);
$names = array_map(
function($person) { return $person['name']; },
$data
);
You see how nicely you can produce array of names.
Last one:
array_reduce(
array_filter($array, function($val) { return $val % 2 == 0; },
function($reduced, $value) { return $reduced*$value; }
)
It calculates product of even numbers.
Some philosophy. What is function? A unit of functionality that can be invoked and unit of code reuse. Sometimes you need only the first part: ability to invoke and do actions, but you don't want to reuse it at all and even make it visible to other parts of code. That's what anonymous functions essentially do.
It is useful especially for callbacks:
array_walk($myArray, function($value, $key) {
// do something
});