Kristofer Doman Kristofer Doman - 1 year ago 46
PHP Question

Best way to call function on every object in array? Without for loop?

I'm curious if there's a better way to do what I'm doing. I'm fairly new to php so I'm interested in what others think who have spent more time with the language.

What I want to do: call a function on every object in an array

What I'm doing:

array_map(function($object) { $object->loadEvents(); }, $patients);

This is fine, and it works. I could also use a for loop,

Why I'm asking: I've become accustomed to not using for loops when I don't have too, so I figured out a way to use array_map. The thing is, every where I look, it seems people are using array_map to map results to a new array. When I basically want the functionality of array_map but without the return values.

Is there a better way? Outside this and a for loop? Is a for loop a better way?

Answer Source

The usual idiom in PHP for looping over an array is the foreach operator. array_walk and array_map can be used, but they didn't become common idioms because until relatively recent versions of PHP creating anonymous functions was inconvenient. Prior to PHP 5.3, you had to call create_function() to create a function on the fly. So array_walk and array_map were usually only used when there's a named function that does what you want, e.g.

$array = array_map('trim', $array);

But even now that you can use function to create anonymous functions, many people find

array_walk($array, function($x) {

less readable than

foreach ($array as $xx) {

array_map tends to be used more than array_walk because it can be used as part of a larger expression. With foreach you would have to use one loop to push onto a result array, then follow it with code to operate on that array.