Definition
The array_map() function applies a callback function to each element of an array and returns a new array with modified elements.
Syntax
array_map(myfunction, array1, array2, array3, ...)
Parameters
Parameter | Description |
---|---|
myfunction |
Required. The name of the user-made function, or null. |
array1 |
Required. Specifies an array. |
array2 |
Optional. Specifies an array. |
array3 |
Optional. Specifies an array. |
Example
<?php
function square($x) {
return($x*$x);
}
$myIntegers = array(1,2,3,4,5);
$mySquares = array_map("square", $myIntegers);
print_r($mySquares);
echo "<br>";
// Another example
function total($price){
$tax = 5/100; // 5%
return ($price *= (1 + $tax));
}
$items = array("bread"=>3, "tea"=>5, "coffee"=>10);
// Applying callback function to each element
$result = array_map("total", $items);
print_r($result);
echo "<br>";