PHP array_map() function

Example

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

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

Run Instance

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 function is applied.

The number of parameters accepted by the callback function should match the number of arrays passed to the array_map() function.

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

Syntax

array_map(myfunction,array1,array2,array3...)
Parameters Description
myfunction Required. The name of the user-defined function, or null.
array1 Required. Defines an array.
array2 Optional. Defines an array.
array3 Optional. Defines an array.

Technical details

Return value: Returns an array containing array1 array of values, after applying a custom function to each value.
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 Instance

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 Instance

Example 3

Convert all letters of the value in the array to uppercase:

<?php
function myfunction($v)
{
$v=strtoupper($v);
  return $v;
}
$a=array("Animal" => "horse", "Type" => "mammal");
print_r(array_map("myfunction",$a));
?>

Run Instance

Example 4

When assigning null to the function name:

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

Run Instance