How to use array map function in PHP?

In this tutorial, you will learn what is the use of the PHP array_map() function and how to use it.

PHP array_map() function

If you want to run a function for each value of an array, you can do so by using the array_map() function.

array_map(callback, array1, array2, array3, ...)
  • callback – The callback parameter takes a function that you want to call for each element of an array.
  • array – After adding a callback, you can pass multiple arrays as arguments. But at least one array is required.

Example of array_map

The array_map() function returns an array with new values returned by the callback function.

<?php
$num = array(1, 2, 3, 4, 5);

function plus_2($val){
    return $val + 2;
}

$numPlus2 = array_map('plus_2', $num);

print_r($numPlus2);
Array       
(
    [0] => 3
    [1] => 4
    [2] => 5
    [3] => 6
    [4] => 7
)

Another Example

<?php
$names = array('john', 'mark', 'henry', 'bob');

function name_upper($name){
    // name return with uppercase letters.
    return strtoupper($name);
}

$newNames = array_map('name_upper', $names);

print_r($newNames);
Array
(
    [0] => JOHN 
    [1] => MARK 
    [2] => HENRY
    [3] => BOB  
)

Example with multiple arrays

<?php
$names = array('john', 'mark', 'henry', 'bob');
$ages = array(21, 52, 34, 47);

function name_with_age($name, $age){
    return "$name is $age years old,";
}

$nameAge = array_map('name_with_age', $names, $ages);

print_r($nameAge);
Array
(
    [0] => john is 21 years old. 
    [1] => mark is 52 years old. 
    [2] => henry is 34 years old.
    [3] => bob is 47 years old.  
)

What if, NULL is passed in the callback parameter?

If you pass NULL in the callback argument, the array_map function merges the values of all the arrays into one multidimensional array.

<?php
$names = array('john', 'mark', 'henry', 'bob');
$ages = array(21, 52, 34, 47);

$nameAge = array_map(NULL, $names, $ages);

print_r($nameAge);
Array
(
    [0] => Array       
        (
            [0] => john
            [1] => 21  
        )

    [1] => Array       
        (
            [0] => mark
            [1] => 52  
        )

    [2] => Array       
        (
            [0] => henry
            [1] => 34
        )

    [3] => Array
        (
            [0] => bob
            [1] => 47
        )

)

Leave a Reply

Your email address will not be published.