PHP
Transform All Elements in a PHP Array Using a Callback
Discover how to apply a custom function to every element in a PHP array, returning a new array with the transformed values, using the `array_map()` function.
<?php
$numbers = [1, 2, 3, 4, 5];
// Double each number
$doubledNumbers = array_map(function($number) {
return $number * 2;
}, $numbers);
echo "Doubled Numbers:
";
print_r($doubledNumbers);
$products = ['apple', 'banana', 'orange'];
// Capitalize each product name
$capitalizedProducts = array_map('ucfirst', $products);
echo "
Capitalized Products:
";
print_r($capitalizedProducts);
// Transform multiple arrays simultaneously
$firstNames = ['John', 'Jane'];
$lastNames = ['Doe', 'Smith'];
$fullNames = array_map(function($first, $last) {
return "$first $last";
}, $firstNames, $lastNames);
echo "
Full Names:
";
print_r($fullNames);
?>
How it works: The `array_map()` function applies a user-defined callback function to each element of one or more arrays. It returns a new array containing the results, without modifying the original array(s). This is a versatile tool for bulk data transformation, allowing you to modify array elements based on custom logic or existing functions.