PHP
Transform All Values in a PHP Array Using a Callback
Discover how to apply a custom function to every element in a PHP array, creating a new array with the transformed values using `array_map()`.
<?php
$numbers = [1, 2, 3, 4, 5];
// Example 1: Square each number
$squaredNumbers = array_map(function($n) {
return $n * $n;
}, $numbers);
echo "Original Numbers: " . implode(', ', $numbers) . "
";
echo "Squared Numbers: " . implode(', ', $squaredNumbers) . "
";
$names = ['alice', 'bob', 'charlie'];
// Example 2: Capitalize first letter of each name
$capitalizedNames = array_map('ucfirst', $names);
echo "Original Names: " . implode(', ', $names) . "
";
echo "Capitalized Names: " . implode(', ', $capitalizedNames) . "
";
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25]
];
// Example 3: Add a currency symbol to prices
$productsWithCurrency = array_map(function($product) {
$product['price'] = '$' . $product['price'];
return $product;
}, $products);
echo "Original Products:
";
print_r($products);
echo "Products with Currency:
";
print_r($productsWithCurrency);
?>
How it works: The `array_map()` function applies a callback function to each element of an array (or arrays) and returns a new array containing the results. This is ideal for bulk transformations of array values without modifying the original array. It can take anonymous functions, built-in PHP functions, or user-defined functions as its callback, providing great flexibility for data manipulation.