In this article, I will explain how to create Anonymous Functions in PHP.
Anonymous functions are those functions that we create without a name. In fact, we can use anonymous functions in a number of places. For instance, suppose we need to pass a function as a parameter to another function. In such a case, first, we create an anonymous function and assign it to a variable. Then, we can pass this variable as a parameter.
Furthermore, we can also define an anonymous function at the place where it needs to be invoked. As a result, the code remains concise. Therefore, the use of anonymous functions simplifies the programs, reduces the lines of code, and eliminates the need of creating a separate file for the function definition.
Examples of Anonymous Functions in PHP
The following code shows a simple anonymous function that returns the sum of two numbers that the function takes as arguments.
<?php
$v=function($x, $y){ return $x+$y;};
echo $v(3, 4);
?>
Output
![](https://www.programmingempire.com/wp-content/uploads/2022/05/image-12.png)
Another example of the anonymous function is shown below. As can be seen, the function array_walk() takes a function as the second parameter which is an anonymous function in this example. It computes the sum of integers from 1 to the value of a specific array element.
<?php
$arr=array(1,2,3,4,5,6,7,8,9,10);
array_walk($arr, function($n){
$s=0;
for($i=1;$i<=$n;$i++){
$s+=$i;
}
echo 'Number: ',$n,' Sum: ',$s,'<br>';});
?>
Output
![Applying Anonymous Function on Elements of an Array](https://www.programmingempire.com/wp-content/uploads/2022/05/image-13.png)
Similarly, the following PHP Script displays the factorial of each element of the array. Here also, the function that computes the factorial is passed as an argument to the array_walk() function.
<?php
$arr=array(6, 8, 12, 9, 5, 6, 4);
$factorials=function($n){
$f=1;
for($i=1;$i<=$n;$i++)
{
$f*=$i;
}
echo 'Factorial of ',$n,' is ',$f,'<br>';
};
array_walk($arr, $factorials);
?>
Output
![Display Factorial of Elements of an Array](https://www.programmingempire.com/wp-content/uploads/2022/05/image-14.png)
The following code shows the use of the anonymous function to find the sum of values of an array in a two-dimensional array.
<?php
$marks=array(array(78, 80, 45, 90, 30),
array(40, 45, 67, 87, 24),
array(28, 60, 37, 45, 73),
array(98, 22, 45, 97, 48),
array(37, 89, 50, 44, 85),
array(76, 56, 87, 24, 24),
array(90, 86, 38, 78, 74));
function Display_Result($m)
{
foreach($m as $a)
{
$c=function($t) use($a){
foreach($t as $k)
{
echo $k.' ';
}
$sum=array_sum($t);
$p=($sum*100)/500;
echo 'Percentage: '.$p.'<br>';
};
}
array_walk($m, $c);
}
Display_Result($marks);
?>
Output
![The Output of the Program to Find the Percentage using Anonymous Functions in PHP](https://www.programmingempire.com/wp-content/uploads/2022/05/image-15.png)