How can array_walk be used to optimize performance in PHP when iterating through arrays?
Using array_walk can optimize performance in PHP when iterating through arrays by allowing you to apply a callback function to each element in the array without the need for a loop. This can make the code more concise and potentially faster than using a traditional loop structure.
// Example of using array_walk to optimize performance
$numbers = [1, 2, 3, 4, 5];
// Define a callback function to square each number
function square(&$value, $key) {
$value = $value * $value;
}
// Apply the callback function to each element in the array
array_walk($numbers, 'square');
// Output the modified array
print_r($numbers);