PHP array_map() Function

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

  1. $callback(required): The callback function to run for each element in each array.
  2. $array1(required): It specifies an array to be modified.
  3. $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 RepresentationVisual Representation of PHP array_map() FunctionExample 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 ArraysVisual Representation of 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 Visual Representation of 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.

Related Posts

PHP array_keys()

PHP array_push()

PHP array_pop()

PHP array_shift()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.