Suppose I've the following function:
function mul()
{
return array_reduce(func_get_args(), '*');
}
Is is possible to use the * operator as a callback function? Is there any other way?
In this specific case, use array_product()
:
function mul() {
return array_product(func_get_args());
}
In the general case? No, you can't pass an operator as a callback to a function. You would at least have to wrap it in a function:
function mul() {
return array_reduce(func_get_args(), 'mult', 1);
}
function mult($a, $b) {
return $a * $b;
}
The code you have provided wouldn't work but you can do something similar.
function mul()
{
return array_reduce(func_get_args(), create_function('$a,$b', 'return "$a * $b'));
}
create_function allows you to create short function (one liner), if your function is getting longer then one statement it's better to create a real function to do the job.
Please also note the single quote are important because you are using dollar symbol so you don't want PHP to try to replace them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With