unkn0wn unkn0wn - 27 days ago 10
PHP Question

Workaround for not having anonymous functions

I have PHP 5.2 and am trying to use this anonymous function

$values = array_map(function ($value) use ($link){
if($value == null) return null;
return mysqli_real_escape_string($link, (string)$value);
}, array_values($input));


Server's response


PHP Error Message
Parse error: syntax error, unexpected T_FUNCTION in MY FILE on line 16



So server wont read this anonymous function, so i gotta define it right?

$func = function ($value) use ($link){
if($value == null) return null;
return mysqli_real_escape_string($link, (string)$value);
};
$values = array_map($func, array_values($input));


Still now working.
Any help?

Answer

Anonymous functions became available as of PHP 5.3, so 5.2 doesn't have them

This should work in all versions of PHP

function array_stuff($value){
    global $link; // I hate this sooo much but necessary evil here
    if($value == null) return null;
    return mysqli_real_escape_string($link, (string)$value);
};
$values = array_map('array_stuff', array_values($input));