PHP
Transform Array Elements with `array_map`
Use PHP's `array_map` function to apply a callback to each element of an array, transforming its values into a new array structure or format, without modifying the original.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'stock' => 50],
['name' => 'Keyboard', 'price' => 75, 'stock' => 200],
['name' => 'Monitor', 'price' => 300, 'stock' => 120],
];
$productSummaries = array_map(function($product) {
return [
'product_name' => strtoupper($product['name']),
'formatted_price' => '$' . number_format($product['price'], 2),
'availability' => $product['stock'] > 0 ? 'In Stock' : 'Out of Stock'
];
}, $products);
print_r($productSummaries);
?>
How it works: This snippet illustrates the use of `array_map` to transform each element of an array. The anonymous function is applied to every product, creating a new associative array for each with modified keys and values (e.g., uppercase name, formatted price, and stock availability status). This is a powerful tool for reformatting data for presentation or integration with other systems, leaving the original array untouched.