Edgar Sampere Edgar Sampere - 3 months ago 14
PHP Question

Understanding anonymous functions PHP

I've been learning web development using php and I'm a little bit confused about the anonymous functions. Specifically concerning the pass of parameters and how they work inside a funcion like that.
For example, in the 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 don't really get how the parameters
$a
and
$b
are used. I think they're taken for comparison in order sort the array for where is defined how the function should use them and take them from?

In a code like the next one

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


I know the parameter is passed directly to the function and used to return the result of the multiplication.

In this post the example of

$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 this is not as complicated as it seems but I'm really confused about the use of the parameters on this kind of functions

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

Let's take this example. When you pass a function to usort(), PHP internally calls it with 2 elements from your array to see which is bigger/smaller.

The $a and $b values come from inside the usort() function. Its code calls the provided function with 2 parameters. Your parameters don't need to be named $a and $b, they can be named whatever you like.