How can the array_map function be used to manipulate array elements in PHP?
The array_map function in PHP can be used to apply a callback function to each element of an array, returning a new array with the modified elements. This can be useful for manipulating array elements without needing to loop through each element manually. Example:
```php
// Define a callback function to manipulate array elements
function square($num) {
return $num * $num;
}
// Original array
$numbers = [1, 2, 3, 4, 5];
// Use array_map to apply the square function to each element
$squaredNumbers = array_map('square', $numbers);
// Output the modified array
print_r($squaredNumbers);
```
This code snippet defines a callback function `square` that squares a number, creates an array of numbers, applies the `square` function to each element using `array_map`, and then outputs the modified array with each number squared.