[PHP] operators as callbacks?

2008-11-29 Thread Joe
Is it possible to use a PHP operator as a callback? Suppose I want to add two
arrays elementwise, I want to be able to do something like this:
 array_map('+', $array1, $array2)
but this doesn't work as + is an operator and not a function.

I can use the BC library's math functions instead:
 array_map('bcadd', $array1, $array2)
but that is an ugly hack that might break if the library is not available.

I can create an anonymous function:
 array_map(create_function('$a, $b', 'return $a + $b;'), $array1, $array2)
but that seems really unnecessarily verbose.

Is there any simple clean way to do it? Thanks,



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP] operators as callbacks?

2008-11-29 Thread Nathan Nobbe
On Sat, Nov 29, 2008 at 2:42 PM, Joe [EMAIL PROTECTED] wrote:

 Is it possible to use a PHP operator as a callback?


not that im aware of, even if you use the operator overloading extension, im
not sure youll find that ability.

I can use the BC library's math functions instead:
  array_map('bcadd', $array1, $array2)
 but that is an ugly hack that might break if the library is not available.


 i dont know how bad that is really, i guess it depends on the distribution
scope of the application.  if its in a controlled environment, id just say
install bcmath and forget it.

I can create an anonymous function:
  array_map(create_function('$a, $b', 'return $a + $b;'), $array1, $array2)
 but that seems really unnecessarily verbose.


well, youll just have to wait for 5.3 and its new lambda notation, youll be
able to do this (something close anyway :)),

array_map(function($a, $b) { return $a + $b; }, $array1, $array2);

it doesnt look like much difference here, but create_function() gets a lot
worse w/ functions any less trivial than adding 2 numbers.

Is there any simple clean way to do it? Thanks,


i think youre beating your head against the wall for no good reason.  your
solutions are fine, just pick one and roll w/ it ;)

-nathan