PHP
Transform Array Elements Using a Callback
Discover how to modify each element in a PHP array and return a new array with the transformed values using the powerful `array_map()` function.
<?php
$numbers = [1, 2, 3, 4, 5];
// Double each number in the array
$doubledNumbers = array_map(function($number) {
return $number * 2;
}, $numbers);
echo json_encode($doubledNumbers, JSON_PRETTY_PRINT);
// Another example: format product prices
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
];
$formattedProducts = array_map(function($product) {
$product['price'] = '$' . number_format($product['price'], 2);
return $product;
}, $products);
echo "
";
echo json_encode($formattedProducts, JSON_PRETTY_PRINT);
// Output for numbers: [2, 4, 6, 8, 10]
// Output for products:
// [
// {
// "name": "Laptop",
// "price": "$1,200.00"
// },
// {
// "name": "Mouse",
// "price": "$25.00"
// }
// ]
?>
How it works: The `array_map()` function applies a callback function to each element of a given array (or arrays) and returns a new array containing the results. This is useful for transforming or reformatting data without altering the original array directly.