tags:

views:

94

answers:

4

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?

+6  A: 

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;
}
cletus
nice one, I never seen that function, wondering if it's a common operation, I never had the chance to use it
RageZ
+5  A: 

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.

RageZ
+1  A: 

If I define your function and then do this:

$arr = array(2,3,4,5,6);
mul($arr);

I get the following warning:

Warning: array_reduce(): The second argument, '*', should be a valid callback in /home/azanar/Documents/Projects/testbed/test.php on line 6

The other two answers here do well at addressing a working way of doing this. However, it is generally a good habit, when you wonder if something is allowed in a particular language, to just try it and see what happens. You might be surprised by what some languages allow, and if they don't, they're almost always going to give you some sort of meaningful error message.

Ed Carrel
+1  A: 

PHP 5.3 has closures ;)

peufeu