PHP

Transforming Array Elements with a Callback

Discover how to apply a transformation to every element in a PHP array using `array_map()`, creating a new array with the modified values.

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

// Apply a 10% tax to each price
$pricesWithTax = array_map(function($price) {
    return $price * 1.10; // Add 10% tax
}, $prices);

echo "Original Prices: " . implode(", ", $prices) . "
";
echo "Prices with Tax: " . implode(", ", $pricesWithTax) . "
";

$users = [
    ['first_name' => 'John', 'last_name' => 'Doe'],
    ['first_name' => 'Jane', 'last_name' => 'Smith'],
];

// Format user names
$formattedUsers = array_map(function($user) {
    return $user['first_name'] . ' ' . strtoupper($user['last_name']);
}, $users);

echo "Formatted Users: " . implode(", ", $formattedUsers) . "
";
?>
How it works: The `array_map()` function applies a user-defined callback function to each element of one or more arrays. It returns a new array containing all the elements after applying the callback function. This is perfect for transforming data, such as formatting values, performing calculations, or extracting specific parts of complex arrays or objects.

Need help integrating this into your project?

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

Hire DigitalCodeLabs