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?
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.
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.
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.
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.
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
You can also use
array_map('Class::method', $array)
syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With