PHP array_map() Function
In this chapter you will learn:
- Definition for PHP array_map() Function
- Syntax for PHP array_map() Function
- Parameter for PHP array_map() Function
- Example - Map an array with user function
- Example - Using a user-made function to change the values of an array
- Example - Change all letters of the array values to uppercase
- Example - Assign null as the function name
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 java2 s .c om*/
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 ja v a2 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/* ja v a 2 s . c o 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/*j a v a2 s.com*/
$a1=array("A","B","java2s.com");
$a2=array("C","B");
print_r(array_map(null,$a1,$a2));
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_merge() function
- Syntax for PHP array_merge() function
- Parameter for PHP array_merge() function
- Note for PHP array_merge() function
- Example - Update associate arrays
- Example - Indexed key got reindexed
- Example - Use array_merge() to reindex an indexed array
- Example - merge associate array
- Example - + vs array_merge()
Home » PHP Tutorial » PHP Array Functions