Latest web development tutorials

PHP array_map () function

PHP Array Reference Complete PHP Array Reference

Examples

The function is applied to each value in the array, each value is multiplied by itself, and returns an array with the new values:

<?php
function myfunction($v)
{
return($v*$v);
}

$a=array(1,2,3,4,5);
print_r(array_map("myfunction",$a));
?>

Running instance »

Definition and Usage

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

Tip: You can enter a function to one or more arrays.


grammar

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

参数 描述
myfunction 必需。用户自定义函数的名称,或者是 null。
array1 必需。规定数组。
array2 可选。规定数组。
array3 可选。规定数组。

technical details

return value: Returns an array array1 values of user-defined function after the action.
PHP version: 4.0.6+


More examples

Example 1

Using a user-defined function to change the value 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));
?>

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

Running instance »

Example 3

All letters to uppercase values ​​in the array:

<?php
function myfunction($v)
{
$v=strtoupper($v);
return $v;
}

$a=array("Animal" => "horse", "Type" => "mammal");
print_r(array_map("myfunction",$a));
?>

Running instance »

Example 4

The function name assignment when null:

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

Running instance »


PHP Array Reference Complete PHP Array Reference