PHP

Transform All Values in a PHP Array Using `array_map()`

Discover how to efficiently apply a callback function to every element of one or more PHP arrays using array_map(), creating a new array with the transformed values.

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

// Example 1: Double each number
$doubledNumbers = array_map(function($n) {
    return $n * 2;
}, $numbers);
print_r($doubledNumbers); // Result: [2, 4, 6, 8, 10]

// Example 2: Convert strings to uppercase
$fruits = ['apple', 'banana', 'cherry'];
$uppercaseFruits = array_map('strtoupper', $fruits);
print_r($uppercaseFruits); // Result: ['APPLE', 'BANANA', 'CHERRY']

// Example 3: Combine elements from multiple arrays
$firstNames = ['John', 'Jane'];
$lastNames = ['Doe', 'Smith'];
$fullNames = array_map(function($firstName, $lastName) {
    return $firstName . ' ' . $lastName;
}, $firstNames, $lastNames);
print_r($fullNames); // Result: ['John Doe', 'Jane Smith']

// Example 4: Modify associative array values
$products = [
    ['name' => 'Laptop', 'price' => 1200],
    ['name' => 'Mouse', 'price' => 25],
];
$productsWithTax = array_map(function($product) {
    $product['price'] *= 1.10; // Add 10% tax
    return $product;
}, $products);
print_r($productsWithTax);
?>
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 the results of applying the callback to each element. This function is incredibly useful for transforming data, such as changing data types, performing calculations, or formatting values, without needing to manually loop through the array. It can also process multiple arrays simultaneously, passing corresponding elements to the callback.

Need help integrating this into your project?

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

Hire DigitalCodeLabs