10

array_map accepts string as its first argument. Is there a way, to use arrays instead of strings, like:

.... array_map( array('trim','urlencode'), $my_array);

so I could attach multiple functions.

LF00
  • 27,015
  • 29
  • 156
  • 295
T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 1
    *"`array_map` accepts string"* -- The first argument of [`array_map()`](http://php.net/manual/en/function.array-map.php) is a [callable](http://php.net/manual/en/language.types.callable.php). There are 6 types of callables in PHP (see the examples on the documentation), you can easily find one that matches your project and coding style. – axiac May 14 '17 at 11:04
  • 1
    One way might be to: `return array_map('trim', array_map('urlencode', $targets));` – tlorens Sep 18 '19 at 16:55

2 Answers2

20

You can define a function to combine these trim and urlencode functions. Then use the new function name or the new function as the first parameter of the array_map() function.

array_map(function($v){
  $v = trim($v);
  $v = urlencode($v);
  return $v
}, $array);
Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
LF00
  • 27,015
  • 29
  • 156
  • 295
2

You can do it this way also. Reference: create_function()

Warning: This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

Try this here code snippet here

$newfunc = create_function('$value', 'return urlencode(trim($value));');
$array=array_map($newfunc, $array);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • 1
    Warning: create_function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged (from the docs your link points to) :-) – 3000 Aug 31 '19 at 14:39
  • $newfunc = function($value) { return urlencode(trim($value)); }; – Alper AKPINAR Feb 07 '23 at 08:39