PHP

Transforming All Array Values with `array_map`

Learn to modify every element in a PHP array by applying a custom transformation function using the versatile `array_map()` function, creating a new array.

<?php
$prices = [10.50, 20.00, 15.75];

// Add tax to each price
$pricesWithTax = array_map(function($price) {
    return round($price * 1.20, 2); // Add 20% tax, round to 2 decimal places
}, $prices);
echo "Prices with Tax:
";
print_r($pricesWithTax);

$names = ['alice', 'bob', 'charlie'];

// Capitalize each name
$capitalizedNames = array_map('ucfirst', $names); // Using a built-in function
echo "
Capitalized Names:
";
print_r($capitalizedNames);

// Transform an array of user objects
$users = [
    ['id' => 1, 'first_name' => 'John', 'last_name' => 'Doe'],
    ['id' => 2, 'first_name' => 'Jane', 'last_name' => 'Smith']
];

$fullNames = array_map(function($user) {
    return $user['first_name'] . ' ' . $user['last_name'];
}, $users);
echo "
Full Names:
";
print_r($fullNames);
?>
How it works: `array_map()` is used to apply a callback function to each element of one or more arrays, returning a new array containing the results. This function is ideal for transforming data without modifying the original array. The examples show how to add a tax percentage to prices, capitalize names using a built-in PHP function (`ucfirst`), and combine first and last names from an array of user data to create full names, demonstrating its flexibility for various transformation needs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs