Apply the function to each value in the array, multiply each value by itself, and return the array with the new value:
<?phpfunction myfunction($v){ return($v*$v);}$a=array(1,2,3,4,5);print_r(array_map("myfunction",$a));?>The array_map() function applies the user-defined function to each value in the array and returns the array with the new values after the user-defined function is applied.
Tip: You can input one or more arrays to the function.
array_map( myfunction, array1, array2, array3 ...)
parameter | describe |
---|---|
myfunction | Required. The name of the user-defined function, or null. |
array1 | Required. Specifies an array. |
array2 | Optional. Specifies an array. |
array3 | Optional. Specifies an array. |
Return value: | Returns an array containing the value of array1 after the user-defined function is applied. |
---|---|
PHP version: | 4.0.6+ |
Use a user-defined function to change the value of an array:
<?phpfunction myfunction($v){if ($v==="Dog") { return "Fido"; }return $v;}$a=array("Horse","Dog","Cat"); print_r(array_map("myfunction",$a));?>Use two arrays:
<?phpfunction 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));?>Change all letters of the values in an array to uppercase:
<?phpfunction myfunction($v) {$v=strtoupper($v); return $v;}$a=array("Animal" => "horse", "Type" => "mammal");print_r(array_map ("myfunction",$a));?>When assigning the function name to null:
<?php$a1=array("Dog","Cat");$a2=array("Puppy","Kitten");print_r(array_map(null,$a1,$a2));?>