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.

2
  • 1
    "array_map accepts string" -- The first argument of array_map() is a callable. 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. Commented May 14, 2017 at 11:04
  • 1
    One way might be to: return array_map('trim', array_map('urlencode', $targets)); Commented Sep 18, 2019 at 16:55

2 Answers 2

21

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);
Sign up to request clarification or add additional context in comments.

2 Comments

for those who not so familar with PHP but wanna learn. $v is now the pointer, and //trim() call // ur.... is ment as $v = trim($v); $v = urlencode($v); return $v;
should be return $v;
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);

2 Comments

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) :-)
$newfunc = function($value) { return urlencode(trim($value)); };

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.