PHP
Transform Array Values with `array_map`
Discover how to apply a callback function to each element of an array in PHP using `array_map()`, creating a new array with transformed values.
<?php
$numbers = [1, 2, 3, 4, 5];
// Double each number
$doubledNumbers = array_map(function($number) {
return $number * 2;
}, $numbers);
print_r($doubledNumbers);
$names = ['alice', 'bob', 'charlie'];
// Capitalize first letter of each name
$capitalizedNames = array_map('ucfirst', $names);
print_r($capitalizedNames);
?>
How it works: The `array_map()` function is used to apply a specified callback function to each element of a given array. It returns a new array containing the results. This snippet shows two examples: doubling each number in an array and capitalizing the first letter of each name in another array, demonstrating its versatility for data transformation.