The php array_map() function gives us the ability to create a new array by applying a function to all elements of one or more arrays.

function square($var) {
    return $var * $var;
}

$array = array(1,2,3,4,5);

print_r(array_map("square", $array));

// Output:
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

When working with collections of data in php, the ability to easily manipulate the elements of arrays.

One such operation is being able to apply a function to each element of an array and create a new array.

The php array_map() function gives us the ability to create new arrays by applying a function to one or more arrays. The callback function will be applied to each element of the input arrays.

Below is a basic example showing how you can use array_map() to create a new array which has the squares of each element of a given array of numbers in php.

function square($var) {
    return $var * $var;
}

$array = array(1,2,3,4,5);

print_r(array_map("square", $array));

// Output:
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

You can also define and pass the callback function directly to array_map().

Below is another example of how you can define and pass a callback function to array_map().

$array = array(1,2,3,4,5);

print_r(array_map(function($var) {
    return $var * $var;
},$array));

// Output:
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

Using a lambda Function as the Callback Function with array_map() in php

When using array_map(), you can pass a lambda function as the callback function.

Let’s rewrite our square function as a lambda function and pass it to array_map().

$array = array(1,2,3,4,5);

print_r(array_map(fn($var): float => $var * $var,$array));

// Output:
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)

Applying a Function to Multiple Arrays with array_map() in php

We can use array_map() and apply a function which will create a new array from more than one array.

Up until this point in the article, we’ve only been working with one input array, but let’s define a function which will operate on two arrays.

One example of this is if we have two arrays and we want to perform element-wise multiplication.

Below is an example of how to do element-wise multiplication with array_map() in php.

$array1 = array(1,2,3,4,5);
$array2 = array(6,7,8,9,10);

print_r(array_map(function($v1,$v2) {
    return $v1 * $v2;
},$array1,$array2));

// Output:
Array
(
    [0] => 6
    [1] => 14
    [2] => 24
    [3] => 36
    [4] => 50
)

Hopefully this article has been useful for you to learn how to use the php array_map() function to apply functions to arrays in php.

Categorized in:

PHP,

Last Update: February 26, 2024