PHP
Transforming PHP Array Elements with `array_map`
Discover how to apply a callback function to each element of a PHP array using `array_map`, creating a new array with transformed values without explicit loops for efficiency.
<?php
$numbers = [1, 2, 3, 4, 5];
// Square each number in the array
$squaredNumbers = array_map(function ($number) {
return $number * $number;
}, $numbers);
echo json_encode($squaredNumbers); // Output: [1,4,9,16,25]
$names = ['alice', 'bob', 'charlie'];
// Capitalize each name
$capitalizedNames = array_map('ucfirst', $names);
echo json_encode($capitalizedNames); // Output: ["Alice","Bob","Charlie"]
?>
How it works: The `array_map()` function applies the callback to each element of the given arrays and returns a new array containing the results. It's an efficient way to transform values in an array without explicitly writing a `foreach` loop. This example shows squaring numbers and capitalizing strings using `array_map()`.