Home >Backend Development >PHP Tutorial >PHP array function array_map() notes_PHP tutorial
Definition and usage
The array_map() function returns the array after the user-defined function is applied. The callback function should accept the same number of arguments as the number of arrays passed to the array_map() function.
Grammar
array_map(function,array1,array2,array3...)
参数 | 描述 |
---|---|
function | 必需。用户自定义函数的名称,或者是 null。 |
array1 | 必需。规定数组。 |
array2 | 可选。规定数组。 |
array3 | 可选。规定数组。 |
Example 1
<?php function myfunction($v) { if ($v === "Dog") { return "Fido"; } return $v; } $a = array("Horse", "Dog", "Cat"); print_r(array_map("myfunction", $a)); ?>
Output:
Array ( [0] => Horse [1] => Fido [2] => Cat )
Example 2
Use multiple parameters:
<?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)); ?>
Output:
Array ( [0] => different [1] => same [2] => different )
Example 3
Please see what happens when the custom function name is set to null:
<?php $a1 = array("Dog", "Cat"); $a2 = array("Puppy", "Kitten"); print_r(array_map(null, $a1, $a2)); ?>
Output:
Array (
[0] => Array ( [0] => Dog [1] => Puppy )
[1] => Array ( [0] => Cat [1] => Kitten )
)