How do you use the array_map function in PHP?

The array_map function is used to apply a callback function to each element in an array and returns a new array where each element is the result of the original array elements after being processed by the callback function.

The usage of the array_map function is as follows:
array_map(callback, array1, array2, …)
Where callback is the callback function applied to array elements, and array1, array2, … are the arrays to be processed.

Example code:

Output:
Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)

In the example above, we defined a callback function called square, which is used to calculate the square of a number. Then, we created an array $numbers containing some numbers. By calling the array_map function and passing the callback function square and the array $numbers as parameters, we obtained a new array $squared_numbers, which contains the square value of each element. Finally, we used the print_r function to print out the new array $squared_numbers.

bannerAds