PHP

Transform Array Elements Using `array_map` and a Callback

Apply a custom function to each element of a PHP array, creating a new array with modified values for various data transformation tasks.

<?php
$products = [
    ['id' => 1, 'name' => 'Laptop', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'price' => 25],
    ['id' => 3, 'name' => 'Keyboard', 'price' => 75]
];

$productsWithFormattedPrice = array_map(function($product) {
    $product['formatted_price'] = '$' . number_format($product['price'], 2);
    return $product;
}, $products);

print_r($productsWithFormattedPrice);
/*
Expected Output:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Laptop
            [price] => 1200
            [formatted_price] => $1,200.00
        )

    [1] => Array
        (
            [id] => 2
            [name] => Mouse
            [price] => 25
            [formatted_price] => $25.00
        )

    [2] => Array
        (
            [id] => 3
            [name] => Keyboard
            [price] => 75
            [formatted_price] => $75.00
        )

)
*/
How it works: `array_map()` applies a user-defined callback function to each element of one or more arrays and returns a new array containing all the results. This is ideal for transforming data. The example shows how to add a new `formatted_price` key to each product array, converting the numeric price into a currency-formatted string, without directly modifying the original array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs