PHP
Transform Associative Array Values with `array_map`
Learn to apply a custom function to every element of an associative array, transforming its values while preserving keys, using `array_map`.
$items = [
'apple' => 10,
'banana' => 5,
'orange' => 8,
];
// Increase all item quantities by 2
$increasedItems = array_map(function($quantity) {
return $quantity + 2;
}, $items);
print_r($increasedItems);
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
];
// Add a 'currency' key to each product
$productsWithCurrency = array_map(function($product) {
$product['price_formatted'] = '$' . number_format($product['price'], 2);
return $product;
}, $products);
print_r($productsWithCurrency);
How it works: `array_map()` applies a callback function to each element of one or more arrays, returning a new array containing the results. It's ideal for transforming values—for example, performing mathematical operations, reformatting strings, or adding new computed properties to elements in an array of associative arrays—without modifying the original array directly.