• :
  • :

PHP array_map: How to use in PHP with examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

What is PHP array_map?

Description

PHP array_map function applies the callback to the elements of the given arrays.

Function Signature

array_map(?callable $callback, array $array, array ...$arrays): array 

Arguments

  • callback – A callable (function) to apply to the elements of the given arrays.
  • array – An array to run through the callable.
  • arrays – An optional variable list of arrays to run through the callable. 

Note

  • The count of the number of arrays passed as arguments and the parameters of the callback function should match. Excess arrays are ignored.
  • The function preserves the keys if and only if one array is passed. In case of more than one array,  the returned array has sequential integer keys.

Return Type

The function returns an array derived as a result of applying the callback to the input arrays.

Errors/Exceptions

The function throws ArgumentCountError if an insufficient number of arguments is provided.

Introduction

Just as the array_filter function in PHP, the PHP array_map is a higher-order function. Recall that a higher-order function is characterized as taking another function, usually a callback as an argument or returns a function. The array_map function takes a callback function, transforming or mapping array elements based on a defined rule or logic. Just like the mathematics function, you probably would remember from your elementary classes.

PHP array_map

Similarly, the array_map in PHP applies a mapping to every element of one or more arrays. This function is a powerful one-liner used frequently in development to write shorter and cleaner code without explicit loops. So, in this article, we will explore the array_map function in PHP. 

Usage Example – PHP array_map

PHP array_map

The following example demonstrates the use of array_map in PHP.

<?php
$numbers = [1,2,3,4,5];
 
 
function square($x) {
    return $x**2;
}
 
$transformed = array_map('square',$numbers);
 
print_r($transformed);
 
/*
OUTPUT
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)
*/
 
?>

Voila! The array_map function uses the square() function as a callback. The function runs over every element and transforms it by raising it to the power of two. We can make this more compact using lambda functions.

Lambda Function – PHP array_map

Lambda functions or anonymous functions are function expressions that lack a function name and are usually ideal as arguments for the higher-order functions. So, let’s see how we can redo the example above using the lambda function.

<?php
$numbers = [1,2,3,4,5];
 
 
$square = function ($x) {
    return $x**2;
};
 
print_r(array_map($square, $numbers));
 
/*
OUTPUT
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)
*/
 
?>
 

Also, as of PHP 7.4.0, this could be made even compact.

<?php
$numbers = [1,2,3,4,5];
 
print_r(array_map(fn($x) => $x**2, $numbers));
 
/*
OUTPUT
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)
*/
?>

Multiple Arrays Usage Example – array_map in PHP

So, as seen in the arguments, we have $arrays argument to input a variable list of arrays. The parameters of the callback function and the arguments should match. Let’s check out a function for mapping Roman Numerals to English Letters.

<?php
$roman_numerals = ["I", "II", "III", "IV", "V"];
$english_numbers = ["One", "Two", "Three", "Four", "Five"];
 
print_r(array_map(fn($rom, $eng) => "The Roman Numeral {$rom} is {$eng} in English", $roman_numerals, $english_numbers));
 
/*
OUTPUT
Array
(
    [0] => The Roman Numeral I is One in English
    [1] => The Roman Numeral II is Two in English
    [2] => The Roman Numeral III is Three in English
    [3] => The Roman Numeral IV is Four in English
    [4] => The Roman Numeral V is Five in English
)
*/
?>

Cool! Isn’t it? To our curiosity, let’s make the two arrays unequal in length and see the robustness of the array_map.

<?php
$roman_numerals = ["I", "II", "III", "IV", "V", "VI"];
$english_numbers = ["One", "Two", "Three", "Four", "Five"];
 
print_r(array_map(fn($rom, $eng) => "The Roman Numeral {$rom} is {$eng} in English", $roman_numerals, $english_numbers));
 
/*
OUTPUT
Array
(
    [0] => The Roman Numeral I is One in English
    [1] => The Roman Numeral II is Two in English
    [2] => The Roman Numeral III is Three in English
    [3] => The Roman Numeral IV is Four in English
    [4] => The Roman Numeral V is Five in English
    [5] => The Roman Numeral VI is  in English
)
*/
?>

So, here’s an important caveat. If arrays are unequal in length, the function will extend the shorter ones by padding NULLS.

Zip Operation – array_map PHP

A zip operation is grouping the arrays’ elements of the same index. A zip function is helpful in grouping multiple arrays by index. The zip operation in PHP could be done by passing the callable as null. The array_map function is robust enough to pad null values if arrays are of unequal lengths. So, let’s see how.

array_map in PHP
<?php
$roman_numerals = ["I", "II", "III", "IV", "V", "VI"];
$english_numbers = ["One", "Two", "Three", "Four", "Five", "Six"];
$numbers = [1, 2, 3, 4, 5, 6];
 
print_r(array_map(null, $roman_numerals, $english_numbers, $numbers));
 
/*
OUTPUT
Array
(
    [0] => Array
        (
            [0] => I
            [1] => One
            [2] => 1
        )
 
    [1] => Array
        (
            [0] => II
            [1] => Two
            [2] => 2
        )
 
    [2] => Array
        (
            [0] => III
            [1] => Three
            [2] => 3
        )
 
    [3] => Array
        (
            [0] => IV
            [1] => Four
            [2] => 4
        )
 
    [4] => Array
        (
            [0] => V
            [1] => Five
            [2] => 5
        )
 
    [5] => Array
        (
            [0] => VI
            [1] => Six
            [2] => 6
        )
 
)
*/
?>

Bingo! We have covered a lot of ground today. That’s it for the article.

Conclusion

Superb! We have seen PHP array_map through examples and explored some important caveats related to it. Also, we have seen zip operation using array_map in PHP. So, we hope that you’ve learned something new today. Stay tuned for more interesting articles and tutorials.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to merge 2 arrays with the same keys in PHP

How to return a specific value in array_walk_recursive PHP function

Difference between array_combine and array_merge in PHP

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.