PHP

Transform Array Values Using a Callback Function

Utilize array_map in PHP to apply a custom function to each element of an array, transforming its values into a new array efficiently.

<?php

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

// Multiply each number by 2
$doubledNumbers = array_map(function($n) {
    return $n * 2;
}, $numbers);

print_r($doubledNumbers);

/*
Output:
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
*/

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

// Capitalize the first letter of each name
$capitalizedNames = array_map(function($name) {
    return ucfirst($name);
}, $names);

print_r($capitalizedNames);

/*
Output:
Array
(
    [0] => Alice
    [1] => Bob
    [2] => Charlie
)
*/

// Convert multiple arrays into a new array of combined values
$a = [1, 2, 3];
$b = ['A', 'B', 'C'];
$c = ['x', 'y', 'z'];

$combinedArray = array_map(function($val1, $val2, $val3) {
    return $val1 . '-' . $val2 . '-' . $val3;
}, $a, $b, $c);

print_r($combinedArray);

/*
Output:
Array
(
    [0] => 1-A-x
    [1] => 2-B-y
    [2] => 3-C-z
)
*/
How it works: The `array_map()` function applies the callback function to each of the elements in the input array(s). It returns a new array containing all the elements after applying the callback function. This is extremely useful for transforming data in a consistent way across an entire array, such as formatting strings, performing mathematical operations, or combining elements from multiple arrays into a new structure. The original array remains unchanged.

Need help integrating this into your project?

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

Hire DigitalCodeLabs