Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method be used as an array_map function

I want to do something like this:

 class Cls {   function fun($php) {     return 'The rain in Spain.';   } }  $ar = array(1,2,3); $instance = new Cls(); print_r(array_map('$instance->fun', $ar));                // ^ this won't work 

but the first argument to array_map is supposed to be the name of the function. I want to avoid writing a wrapper function around $instance->fun, but it doesn't seem like that's possible. Is that true?

like image 973
allyourcode Avatar asked Jul 03 '09 01:07

allyourcode


People also ask

What is array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

What exactly is the the difference between array_map Array_walk and Array_filter?

The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.

How to use map array in PHP?

Definition and UsageThe array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. Tip: You can assign one array to the function, or as many as you like.

Does array map preserve keys?

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.


2 Answers

Yes, you can have callbacks to methods, like this:

array_map(array($instance, 'fun'), $ar) 

see the callback type in PHP's manual for more info

like image 72
Jani Hartikainen Avatar answered Sep 22 '22 13:09

Jani Hartikainen


You can also use

array_map('Class::method', $array)  

syntax.

like image 37
Metronom Avatar answered Sep 23 '22 13:09

Metronom