Easy Tutorial
❮ Php Preg_Match_All Func Zip Entry Compressedsize ❯

PHP array_map() Function

Complete PHP Array Reference Manual

Example

Apply a 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));
?>

Definition and Usage

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

Tip: You can input one or multiple arrays to the function.


Syntax

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 of array1 after the user-defined function has been applied.
PHP Version: 4.0.6+
--- ---

More Examples

Example 1

Change the values of the array using a user-defined function:

<?php
function myfunction($v)
{
    if ($v==="Dog")
    {
        return "Fido";
    }
    return $v;
}

$a=array("Horse","Dog","Cat");
print_r(array_map("myfunction",$a));
?>

Example 2

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

Example 3

Convert all letters of the values 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));
?>

Example 4

Assign the function name as null:

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

❮ Php Preg_Match_All Func Zip Entry Compressedsize ❯