← Back to all snippets
PHP

Transforming Array Values with array_map()

Discover how to use PHP's array_map() function to apply a callback to each element of an array, creating a new array with transformed values.

<?php
$prices = [100, 25, 75, 300];
$taxRate = 0.20;

$pricesWithTax = array_map(function($price) use ($taxRate) {
    return $price * (1 + $taxRate);
}, $prices);

print_r($pricesWithTax);
?>
How it works: This example illustrates `array_map()`, which applies a user-defined callback function to every element of an array. Here, it calculates new prices by adding a tax rate to each original price, returning a new array with these adjusted values without 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