views:

53

answers:

3

Hello,

I'm trying to use array_walk with an anonymous function, but I always get the error

 // Parse error: syntax error, unexpected T_FUNCTION in ... on line X
 if(!empty($myArray)) {
   array_walk($myArray, function(&$value, $key){ // Line X
     $value = '"'.$value.'"'; // Add quotes
   });
 }

The surrounding file syntax is correct. Any thoughts?

+3  A: 

Check your PHP version... Anonymous functions are only available since 5.3...

Macmade
Oh, I had no idea this was a version issue. Thanks!
Jasie
+3  A: 

Yes, true anonymous functions (closures) are only available from PHP 5.3, however you can still create an anonymous function in earlier versions of PHP using the create_function() call, which can be used with array_walk(). Something like:

array_walk($myArray, create_function('&$value,$key', '$value = \'"\'.$value.\'"\';'));
w3d
Thanks, never knew about that.
Jasie
A: 

It is not recommendable to use create_function because it is notoriously slow and may be subject to code injection (and is somehow strange to read).

Instead one should define a normal function and pass it's name as value.

Actually, I'm working on a project to allow PHP 5.3 syntax in PHP 5.2, but this is far from being finished. http://github.com/nikic/prephp

nikic