The array_map() function maps each value of an array by using a user function and returns an array with the mapped values.
PHP array_map() Function has the following syntax.
array_map(myfunction,array1,array2,array3...)
Parameter | Is Required | Description |
---|---|---|
myfunction | Required. | The name of the user function |
array1 | Required. | An array |
array2 | Optional. | An array |
array3 | Optional. | An array |
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.
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.
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.
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.