PHP array_map() function is used to modify all the elements of one or more arrays according to user-defined function.
Syntax
array_map($callback,$array1,$array2,$array3...)
Parameters
- $callback(required): The callback function to run for each element in each array.
- $array1(required): It specifies an array to be modified.
- $array2, $array3(optional): They also specify the arrays to be modified.
Return Value
It returns a new array containing the values of array1 after applying the user-defined function to each one.
Visual RepresentationExample 1: How to Use array_map() function
<?php
function square($x)
{
return($x * $x);
}
$arr = [1,3,5,7,9];
$result = array_map("square",$arr);
print_r($result);
Output
Array
(
[0] => 1
[1] => 9
[2] => 25
[3] => 49
[4] => 81
)
Example 2: Using Multiple Arrays
<?php
function subtractAdd($a, $b, $c) {
return $a - $b + $c;
}
$arr = [19, 21, 46, 29];
$arr2 = [18, 19, 20, 21];
$arr3 = [1, 2, 26]; // This array has only 3 elements
$result = array_map("subtractAdd", $arr, $arr2, $arr3);
print_r($result);
Output
Array
(
[0] => 2 //19 - 18 + 1
[1] => 4 //21 - 19 + 2
[2] => 52 //46 - 20 + 26
[3] => 8 // 29 - 21 + 0
)
Example 3: Creating an array of arrays
<?php
$arr = [19, 21, 46, 29];
$arr2 = ['A', 'K', 'B', 'V'];
$result = array_map(null, $arr, $arr2);
print_r($result);
Output
Array
(
[0] => Array
(
[0] => 19
[1] => A
)
[1] => Array
(
[0] => 21
[1] => K
)
[2] => Array
(
[0] => 46
[1] => B
)
[3] => Array
(
[0] => 29
[1] => V
)
)
Example 4: Using a lambda function
<?php
$myfunc = function($value) {
return $value * 5;
};
print_r(array_map($myfunc, range(1, 5)));
Output
Array
(
[0] => 5
[1] => 10
[2] => 15
[3] => 20
[4] => 25
)
We have used the $myfunc as a lambda function and range() function to provide the value between 1 to 5.