PHP

Transform All Values in a PHP Array with array_map

Use `array_map()` to apply a callback function to every element of one or more PHP arrays, creating a new array with transformed values.

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

// Square each number
$squaredNumbers = array_map(function($number) {
    return $number * $number;
}, $numbers);
// $squaredNumbers will be [1, 4, 9, 16, 25]

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

// Capitalize first letter of each name using a built-in function
$capitalizedNames = array_map('ucfirst', $names);
// $capitalizedNames will be ['Alice', 'Bob', 'Charlie']

// Combine two arrays into a new one using a callback
$firstNames = ['John', 'Jane'];
$lastNames = ['Doe', 'Smith'];

$fullNames = array_map(function($first, $last) {
    return $first . ' ' . $last;
}, $firstNames, $lastNames);
// $fullNames will be ['John Doe', 'Jane Smith']
?>
How it works: The `array_map()` function is used to apply a specified callback function to each element of one or more arrays. It iterates through the input array(s) and creates a new array containing the values returned by the callback for each element. This is highly efficient for transforming data, such as modifying strings, performing calculations, or combining elements from multiple arrays into a new structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs