PHP
Transform Associative Arrays with array_map
Discover how to use `array_map` to iterate and transform each associative array within a larger array, modifying existing values or adding new calculated fields in PHP.
<?php
$products = [
['id' => 101, 'name' => 'Laptop', 'price' => 1200],
['id' => 102, 'name' => 'Mouse', 'price' => 25],
['id' => 103, 'name' => 'Keyboard', 'price' => 75]
];
// Add a 'discounted_price' field to each product (10% discount)
$transformedProducts = array_map(function($product) {
$product['discounted_price'] = $product['price'] * 0.90;
return $product;
}, $products);
print_r($transformedProducts);
/* Output:
Array
(
[0] => Array
(
[id] => 101
[name] => Laptop
[price] => 1200
[discounted_price] => 1080
)
[1] => Array
(
[id] => 102
[name] => Mouse
[price] => 25
[discounted_price] => 22.5
)
[2] => Array
(
[id] => 103
[name] => Keyboard
[price] => 75
[discounted_price] => 67.5
)
)*/
How it works: This snippet illustrates how to transform each element of an array of associative arrays using `array_map()`. The function applies a callback to every item in the `$products` array. In this example, the callback takes each product array, calculates a new `discounted_price`, adds it as a new key-value pair, and returns the modified product array. This effectively creates a new array where each original product has been enhanced with additional data.