PHP
How to Transform Array Values Using `array_map` in PHP
Learn to apply a callback function to every element of an array, creating a new array with transformed values. Perfect for data sanitization or formatting.
<?php
$numbers = [1, 2, 3, 4, 5];
// Example 1: Double each number
$doubledNumbers = array_map(function($number) {
return $number * 2;
}, $numbers);
echo "Doubled numbers: " . implode(', ', $doubledNumbers) . "
"; // Output: Doubled numbers: 2, 4, 6, 8, 10
$names = ['alice', 'bob', 'charlie'];
// Example 2: Capitalize each name
$capitalizedNames = array_map('ucfirst', $names);
echo "Capitalized names: " . implode(', ', $capitalizedNames) . "
"; // Output: Capitalized names: Alice, Bob, Charlie
// Example 3: Transform associative array values
$products = [
['name' => 'Laptop', 'price' => 1200.50],
['name' => 'Mouse', 'price' => 25.00],
['name' => 'Keyboard', 'price' => 75.25],
];
$productsWithTax = array_map(function($product) {
$product['price_with_tax'] = $product['price'] * 1.20; // Add 20% tax
return $product;
}, $products);
print_r($productsWithTax);
?>
How it works: The `array_map()` function is used to apply a specified callback function to each element of an array, returning a new array containing the results. This snippet shows how to double numeric values, capitalize string values using a built-in function, and add a new calculated field to elements of an associative array, demonstrating its versatility for data transformation.