Understanding PHP Anonymous Functions

I am learning web development using php and I am a bit confused about anonymous functions. In particular, it concerns the passage of parameters and how they work inside such a function. For example, in code

$array = array("really long string here, boy", "this", "middling length", "larger"); usort($array, function($a, $b) { return strlen($a) - strlen($b); }); print_r($array); 

I really don't understand how the parameters $a and $b . I think they are taken for comparison to sort the array for where it is determined how the function should use them and take them?

In code like the following

 $mult = function($x) { return $x * 5; }; echo $mult(2); 

I know that the parameter is passed directly to the function and is used to return the result of the multiplication.
This post is an example.

 $arr = range(0, 10); $arr_even = array_filter($arr, function($val) { return $val % 2 == 0; }); $arr_square = array_map(function($val) { return $val * $val; }, $arr); 

where is the variable $val taken from?

I know, maybe it’s not as difficult as it seems, but I really got confused in using parameters for such functions

+6
source share
2 answers
 usort($array, function($a, $b) { return strlen($a) - strlen($b); }); 

Take this example. When you pass the usort() function, PHP internally calls it with two elements from your array to see what is bigger / smaller.

The values ​​of $a and $b come from the usort() function. Its code calls the provided function with two parameters. Your parameters should not be called $a and $b , they can be called anything you like.

+9
source

Your question is not about anonymous functions, but about passing calllables.

Take the first of the examples you have reviewed.

 usort($array, function($a, $b) { return strlen($a) - strlen($b); }); 

Let reorganize it a bit, replacing the anonymous function with a named function.

 function compareAB($a, $b) { return strlen($a) - strlen($b); } usort($array, 'comapreAB'); 

As you can see, you can still ask how $a and $b are transferred.

Well, the answer is very simple. usort expects you to provide a callable code that takes 2 arguments, and it calls it internally.

+1
source

All Articles