PHP

Transform Array Values Using array_map

Discover how to apply a callback function to every element in a PHP array, creating a new array with transformed values using `array_map`.

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

// Add a 'discounted_price' to each product (10% off)
$discountedProducts = array_map(function($product) {
    $product['discounted_price'] = $product['price'] * 0.90;
    return $product;
}, $products);

echo "Original Products:
";
print_r($products);
echo "Discounted Products:
";
print_r($discountedProducts);

$numbers = [1, 2, 3, 4, 5];

// Double each number
$doubledNumbers = array_map(function($number) {
    return $number * 2;
}, $numbers);

echo "
Original Numbers: " . implode(", ", $numbers) . "
";
echo "Doubled Numbers: " . implode(", ", $doubledNumbers) . "
";
?>
How it works: The `array_map()` function applies a user-defined callback function to every element of one or more arrays, returning a new array containing the results. This is invaluable for transforming data, such as calculating new values for existing elements, formatting strings, or restructuring array items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs