13

I want to run 3 native functions on the same array: trim, strtoupper and mysql_real_escape_string. Can this be done?

Trying to pass an array as a callback like this isn't working:

$exclude = array_map(array('trim','strtoupper','mysql_real_escape_string'), explode("\n", variable_get('gs_stats_filter', 'googlebot')));

Although this works fine because it's only using one native function as the callback:

$exclude = array_map('trim', explode("\n", variable_get('gs_stats_filter', 'googlebot')));
J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94

3 Answers3

13

You'll have to do it like this:

$exclude = array_map(function($item) {
    return mysql_real_escape_string(strtoupper(trim($item)));
}, explode("\n", variable_get('gs_stats_filter', 'googlebot')));
  • That's what I had figured; that I'd need to end up writing a separate function for the callback. Unfortunately I'm still stuck on PHP 5.2.17 so I had to make a non-anonymous function, BUT, it still works great. Thanks! =) – J. Scott Elblein Jan 06 '12 at 23:28
5

You could also do something like:

  $exclude = array_map(function($item) {
     return trim(strtoupper(mysql_real_escape_string($item)));
  }, explode(...));

or something. Pass in an anonymous function that does all that stuff.

Hope that helps.

Good luck :)

Jemaclus
  • 2,356
  • 1
  • 15
  • 13
5

Yes, just pass the result of one mapping into another:

$result = array_map(
    'mysql_real_escape_string',
    array_map(
        'trim',
        array_map(
            'strtoupper',
            $your_array
        )
    )
);

You can also use a callback in PHP 5.3+:

$result = array_map(function($x){
    return mysql_real_escape_string(trim(strtoupper($x)));
}, $your_array);

or earlier (in versions of PHP lower than 5.3):

$result = array_map(
    create_function('$x','return mysql_real_escape_string(trim(strtoupper($x)));'),
    $your_array
);
Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • 1
    @TimCooper: I am showing possible solutions - there are at least 3 of them, if `array_map` has to be used. But yes, indeed PHP makes it not optimal, because it walks the array (each time it is different) 3 times and returns whole array 3 times. – Tadeck Jan 06 '12 at 23:19