Pass each value of an array to a function to multiply each value by itself, and return an array with the resulting values.
<?php function myfunction($v) { return($v*$v); } $a=array(1,2,3,4,5); print_r(array_map(“myfunction”,$a)); ?> |
The array_map() function passes each value of an array to a user-defined function and returns a new array with the values modified by that function.
Tip: You can provide one array or multiple arrays to the function.
array_map(myfunction, array1, array2, array3, …) |
Parameter |
Description |
myfunction |
Required. The name of the user-defined function or |
array1 |
Required. Specifies an array. |
array2 |
Optional. Specifies an additional array. |
array3 |
Optional. Provides an array. |
Return Value: |
Returns an array with the values from |
PHP Version: |
4.0.6+ |
Using a user-defined function to modify the values of an array:
<?php function myfunction($v) { if ($v===“Dog”) { return “Fido”; } return $v; } $a=array(“Horse”,“Dog”,“Cat”); print_r(array_map(“myfunction”,$a)); ?> |
Using two arrays:
<?php function myfunction($v1,$v2) { if ($v1===$v2) { return “same”; } return “different”; } $a1=array(“Horse”,“Dog”,“Cat”); $a2=array(“Cow”,“Dog”,“Rat”); print_r(array_map(“myfunction”,$a1,$a2)); ?> |
Convert all letters in the array values to uppercase:
<?php function myfunction($v) { $v=strtoupper($v); return $v; } $a=array(“Animal” => “horse”, “Type” => “mammal”); print_r(array_map(“myfunction”,$a)); ?> |
Set the function name to null:
<?php $a1=array(“Dog”,“Cat”); $a2=array(“Puppy”,“Kitten”); print_r(array_map(null,$a1,$a2)); ?> |