PHP array map

PHP array map

Last Updated on Feb 14, 2023

What is array map?

array_map is a function in php that lets you apply a function to the elements of the given arrays and returns an array with changed elements.

and the syntax is like this:

array_map(function, array);

Predefined Function

The function can be a predefined function. In this case you should write the name of the function like a string.

function addHashtag($item){
    return '#' . $item;
}
$names = ['vitto','simon','pratham','hassib','thomas','tom'];
$hashtagged = array_map("addHashtag",$names);
// hashtagged array is:
// ['#vitto','#simon','#pratham','#hassib','#thomas','#tom'];

Anonymous Function

Or it can be an anonymous function.

$names = ['vitto','simon','pratham','hassib','thomas','tom'];
$uppercased = array_map(function($item){
    return strtoupper($item);
},$names);
// uppercased array is:
// ['VITTO','SIMON','PRATHAM','HASSIB','THOMAS','TOM'];

array_map helps you avoid writing something like this

$names = ['vitto','simon','pratham','hassib','thomas','tom'];
$uppercasedNames = [];
foreach($names as $name){
    // add the uppercased name to the array
    $uppercasedNames[] = strtoupper($name);
}

So instead you can write something like this

$names = ['vitto','simon','pratham','hassib','thomas','tom'];
$uppercased = array_map(function($item){
    return strtoupper($item);
},$names);

do you see how shorter and cleaner it is?

Conclusion

Now you know about array map in PHP.

I recommend you to open a PHP files and try to apply a function to every elements in an array.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  •  array map function in PHP
  • predefined and anonymous function in array map

Category: programming

Tags: #php #array

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses