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/*from  w w  w . j ava 2s. co  m*/
    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/*from  www  .  j av a  2  s . co m*/
    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//w w  w. jav a 2s .  co  m
    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//  ww w .ja v a2s. co  m
    $a1=array("A","B","java2s.com");
    $a2=array("C","B");
    print_r(array_map(null,$a1,$a2));
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions