PHP Tutorial - PHP array_map() Function






Definition

The array_map() function maps each value of an array by using a user function and returns an array with the mapped values.

Syntax

PHP array_map() Function has the following syntax.

array_map(myfunction,array1,array2,array3...)

Parameter

ParameterIs RequiredDescription
myfunctionRequired.The name of the user function
array1Required.An array
array2Optional.An array
array3Optional.An array




Example 1

Map an array with user function


<?php
    function myfunction($v){
      return($v*$v);
    }
    
    $a=array(1,2,3,4,5);
    print_r(array_map("myfunction",$a));
?>

The code above generates the following result.





Example 2

Using a user-made function to change the values of an array:


<?php// w  w w  . ja  v  a 2  s  .  c  om
    function myfunction($v){
        if ($v==="java2s.com"){
          return "JAVA2S.COM";
        }
        return $v;
    }
    
    $a=array("Java","java2s.com","PHP");
    print_r(array_map("myfunction",$a));
?>

The code above generates the following result.

Example 3

Change all letters of the array values to uppercase:


<?php
    function myfunction($v){
        $v=strtoupper($v);
        return $v;
    }
    
    $a=array("j" => "java2s.com", "p" => "PHP");
    print_r(array_map("myfunction",$a));
?>

The code above generates the following result.

Example 4

Assign null as the function name:


<?php
    $a1=array("A","B","java2s.com");
    $a2=array("C","B");
    print_r(array_map(null,$a1,$a2));
?>

The code above generates the following result.