Open In App

PHP | array_map() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

Syntax:

array_map(functionName,arr1,arr2...)

Parameters used:
This function takes 2 compulsory parameter functionName and arr1 and the rest are optional.

  • functionName(mandatory): This parameter defines the name of the user-defined function according to which the values in the array will be modified.
  • arr1(mandatory): This parameter specifies the array to be modified.
  • arr2(mandatory): This parameter specifies the array to be modified.

The functionName parameter is compulsory and we can pass any number of arrays to this function named arr1, arr2.. arrn and so on.

Return type : This function returns an array containing all the elements of arr1 after applying the user_function() to each one.

Below program illustrates the working of array_map() function in PHP:




<?php
  
function fun1($v)
{
  return ($v + 7);     // add 7 
}
  
function fun2($v1,$v2)
{
    if ($v1 == $v2) return 1;     
    else return 0;  
}
  
$arr1 = array(1, 2, 3, 4, 5);
$arr2 = array(1, 3, 3, 4, 8);
  
print_r(array_map("fun1", $arr1));
  
print_r(array_map("fun2", $arr1, $arr2));
  
  
?>


Output:

Array
(
    [0] => 8
    [1] => 9
    [2] => 10
    [3] => 11
    [4] => 12
)
Array
(
    [0] => 1
    [1] => 0
    [2] => 1
    [3] => 1
    [4] => 0
)

Creating an array of arrays using array_map(): We can also use the array_map() function in PHP to create array of arrays. To do this we have to pass null as parameter in place of functionName parameter and the list of arrays to create an array of arrays.

Below program illustrates how to create an array of arrays:




<?php
$a = array(1, 2, 3);
$b = array("one", "two", "three");
  
$result = array_map(null, $a, $b);
  
print_r($result);
?>


Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
        )

)


Last Updated : 06 Jan, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads