PHP array_map Function: Usage & Examples
The array_map function is used to apply a callback function to each element in an array. It will return a new array where each element is the result of applying the callback function to each element of the original array.
The syntax of the array_map function is as follows:
Use the callback function to process each element in the arrays provided as arguments, such as array1 and array2.
The sample code is shown below:
function square($n) {
return $n * $n;
}
$numbers = [1, 2, 3, 4, 5];
$squaredNumbers = array_map("square", $numbers);
print_r($squaredNumbers);
Output:
Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)
In the example above, we defined a callback function called “square” to calculate the square of a number. Then, we applied this callback function to each element in the $numbers array using the array_map function, resulting in a new array called $squaredNumbers which contains the square values of each element. Finally, we printed the contents of the new array using the print_r function.