PHP

Transform Array Values with a Custom Function

Apply a user-defined callback function to each element of a PHP array using `array_map()`, returning a new array with all the transformed values.

<?php

$products = [
    ['name' => 'Laptop', 'price' => 1200],
    ['name' => 'Mouse', 'price' => 25],
    ['name' => 'Keyboard', 'price' => 75],
];

// Add a 10% tax to each product price
$productsWithTax = array_map(function($product) {
    $product['price'] = round($product['price'] * 1.10, 2);
    return $product;
}, $products);

print_r($productsWithTax);

// Output:
// Array
// (
//     [0] => Array
//         (
//             [name] => Laptop
//             [price] => 1320
//         )
//     [1] => Array
//         (
//             [name] => Mouse
//             [price] => 27.5
//         )
//     [2] => Array
//         (
//             [name] => Keyboard
//             [price] => 82.5
//         )
// )
How it works: The `array_map()` function is used here to transform each element of an array. It takes a callback function and one or more arrays as arguments. The callback is applied to each element, and a new array containing the modified elements is returned, leaving the original array unchanged. This is ideal for tasks like formatting data, calculations, or adding new properties.

Need help integrating this into your project?

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

Hire DigitalCodeLabs