PHP

Transform Array Values with a Callback Function

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

<?php
$prices = [10, 20, 30, 40, 50];

$discountedPrices = array_map(function($price) {
    return $price * 0.9;
}, $prices);

print_r($discountedPrices);
// Output: Array ( [0] => 9 [1] => 18 [2] => 27 [3] => 36 [4] => 45 )
How it works: The `array_map` function is perfect for transforming each value in an array. It applies a specified callback function to every element of the input array(s) and returns a new array containing the results. This snippet shows a common use case: applying a discount to a list of prices.

Need help integrating this into your project?

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

Hire DigitalCodeLabs