← Back to all snippets
PHP

Transforming Array Elements with array_map

Discover how to apply a transformation function to every element in a PHP array using array_map() to create a new array with modified values.

<?php
$items = [
    ['name' => 'Apple', 'price' => 1.50],
    ['name' => 'Banana', 'price' => 0.75],
    ['name' => 'Orange', 'price' => 1.20],
];

// Add a 'total_price' based on a quantity of 2 for each item
$itemsWithTotalPrice = array_map(function($item) {
    $item['total_price'] = $item['price'] * 2;
    return $item;
}, $items);

print_r($itemsWithTotalPrice);

// Another example: convert string values to uppercase
$fruits = ['apple', 'banana', 'cherry'];
$uppercaseFruits = array_map('strtoupper', $fruits);
print_r($uppercaseFruits);
?>
How it works: This code snippet illustrates the use of `array_map()` to transform each element of an array. The first example modifies an array of associative arrays by adding a new key (`total_price`) based on existing values. The second example shows a simpler use case, converting all string elements in a numeric array to uppercase using a built-in PHP function. `array_map()` returns a new array containing the results of applying the callback function to each original element.

Need help integrating this into your project?

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

Hire DigitalCodeLabs