← Back to all snippets
PHP

Transform All Elements in an Array Using `array_map`

Learn how to apply a callback function to each element of an array and return a new array with the modified elements, perfect for data transformation and manipulation in PHP using `array_map`.

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

// Example 1: Double each number
$doubledNumbers = array_map(function($n) {
    return $n * 2;
}, $numbers);
echo "Doubled numbers:
";
print_r($doubledNumbers);

$items = [
    ['name' => 'Laptop', 'price' => 1200, 'currency' => 'USD'],
    ['name' => 'Keyboard', 'price' => 75, 'currency' => 'USD'],
    ['name' => 'Mouse', 'price' => 25, 'currency' => 'USD']
];

// Example 2: Add a formatted price string to each item
$formattedItems = array_map(function($item) {
    $item['formatted_price'] = $item['currency'] . ' ' . number_format($item['price'], 2);
    return $item;
}, $items);
echo "
Items with formatted price:
";
print_r($formattedItems);

// Example 3: Convert all string values in an array to uppercase
$userProfile = ['first_name' => 'john', 'last_name' => 'doe', 'email' => '[email protected]'];
$uppercaseProfile = array_map('strtoupper', $userProfile);
echo "
Uppercase user profile:
";
print_r($uppercaseProfile);
?>
How it works: The `array_map()` function is used to apply a user-defined callback function to every element of one or more arrays. It returns a new array containing all the modified elements. This is incredibly powerful for transforming data, such as changing data types, formatting values, or adding new calculated properties to elements in an array of associative arrays, without needing to manually loop.

Need help integrating this into your project?

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

Hire DigitalCodeLabs