PHP array_map()Functions

PHP Array ReferenceComplete PHP Array Reference Manual

Examples

Apply the function to each value in the array, multiply each value by itself, and return an array with the new values:

<?php function myfunction($num) { return($num*$num); } $a=array(1,2,3,4,5); print_r(array_map("myfunction",$a)); ?>

Run Example »

Definition and Usage

The array_map() function applies a user-defined function to each value in the array, and returns an array with new values after the user-defined function has been applied.

Tip:You can pass one or more arrays to the function.


Syntax

array_map(myfunction,array1,array2,array3...)

Parameter Description
myfunction Required. The name of the user-defined function, or null.
array1 Required. Specifies the array.
array2 Optional. Specifies the array.
array3 Optional. Specifies the array.

Technical Details

Return value: Returns an array containing the values after the user-defined function has been appliedarray1array of values.
PHP Version: 4.0.6+


More Examples

Example 1

Use a user-defined function to change the values of the array:

<?php function myfunction($v) { if ($v==="Dog") { return "Fido"; } return $v; } $a=array("Horse","Dog","Cat"); print_r(array_map("myfunction",$a)); ?>

Run Example »

Example 2

Use 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)); ?>

Run Example »

Example 3

Change 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)); ?>

Run Example »

Example 4

When the function name is set to null:

<?php $a1=array("Dog","Cat"); $a2=array("Puppy","Kitten"); print_r(array_map(null,$a1,$a2)); ?>

Run Example »


PHP Array ReferenceComplete PHP Array Reference Manual Other Extensions