How to map a function to each element of an array in PHP?

In PHP, you can use the array_map() function to map a function to each element of an array. Here is an example on how to do it:

// Example function to be mapped function square($num) { return $num ** 2; } // Example array $numbers = [1, 2, 3, 4, 5]; // Apply the square function to each element of the array $squaredNumbers = array_map("square", $numbers); // Output the result print_r($squaredNumbers);

Output:

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

In this example, the square() function is defined to square a number. The array_map() function is then used to apply the square() function to each element of the $numbers array. The resulting array of squared numbers is stored in the $squaredNumbers variable. Finally, the print_r() function is used to output the result.