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
Parameter | Is Required | Description |
---|---|---|
myfunction | Required. | The name of the user function |
array1 | Required. | An array |
array2 | Optional. | An array |
array3 | Optional. | 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.