Multiple functions using array_map [duplicate]
Asked Answered
A

2

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.

Aegrotat answered 14/5, 2017 at 10:47 Comment(2)
"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.Antigen
One way might be to: return array_map('trim', array_map('urlencode', $targets));Accident
G
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);
Grundyism answered 14/5, 2017 at 10:55 Comment(2)
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;Alexina
should be return $v;Chiromancy
U
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);
Uxorial answered 14/5, 2017 at 11:16 Comment(2)
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) :-)Sepaloid
$newfunc = function($value) { return urlencode(trim($value)); };Tetrahedron

© 2022 - 2024 — McMap. All rights reserved.