5

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?

2
  • 1
    least. useful. question. name. ever. ;) Commented Nov 7, 2009 at 10:22
  • Fixed title, feel free to revert back if you don't like it Commented Nov 7, 2009 at 10:51

4 Answers 4

8

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice one, I never seen that function, wondering if it's a common operation, I never had the chance to use it
5

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.

Comments

1

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.

Comments

0

PHP 5.3 has closures ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.