Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Anonymous function with array_walk

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?

like image 657
atp Avatar asked Jul 07 '10 18:07

atp


2 Answers

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.\'"\';'));
like image 112
MrWhite Avatar answered Sep 22 '22 06:09

MrWhite


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

like image 45
Macmade Avatar answered Sep 25 '22 06:09

Macmade