Categories
Software Development Web Development

Php how to use array_map with an anonymous function

In PHP you can use array_map() and the other array related methods like array_filter() with either a named function, an anonymous function, or an arrow function.
I didn’t see any examples in the PHP docs( they can be updated any day ) about how to use an anonymous function, so I tried it and here is how to do it. It does show how to use an arrow function which is a shorter way to accomplish this, but looks different. It is a preference thing, both work the same under the hood.

Below is the array_map function definition from the PHP docs.
array_map(?callable $callback, array $array, array ...$arrays): array
As you can see it takes a callable/callback function. This means you could create a function and supply it to this method. And that is a great way to do this… unless what you need to do in the function is very small.
For example I needed to remove the word “Repository” from every file name. I globbed the file names from the directory then I use this function


private function getRepositoryNames(): array{
$values = array_map(function ($val){
return str_replace('Repository', '', $val);
}, $this->_repositoryNames);

dump($values);
return $values;
}

Look closely and you will see the anonymous function. It is the first argument to the array_map() method. The second argument is the actual array I want to work on here. As you can see this would quickly become hard to read if the function were more than a few lines of code. You see this a lot more often in languages like Javascript and Scala.

As you can see I am simply using str_replace() If I needed to do much more it would be better to have a separate named function instead of an anonymous one for several reasons. The #1 reason to separate out the function is for readability purposes. The #2 I can think of relates to #1, maintaining or changing how the function works. But mostly if it is long separate it out so it is easier to read the code.

How does it work?

Basically the way array_map works is the second value you supply, an array, is looped over and supplied to your function one at a time and your function operates on it and returns it to array_map. When array_map is done looping over all the values it returns the new array. You can read more in the PHP docs here.

Links

A very good in depth article about using Php Arrow functions.

Php Anonymous Functions, what are they and why use them. – a very good in depth article about php anonymous functions. It is 10 years old, but still up to date and relevant.

Anonymous and Arrow functions in PHP – a very good article that covers both.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.