PHP

Transform PHP Array Elements with `array_map`

Discover how to use `array_map` in PHP to apply a callback function to every element of an array, creating a new array with the transformed values.

<?php

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

// Double each number in the array
$doubledNumbers = array_map(function($number) {
    return $number * 2;
}, $numbers);

print_r($doubledNumbers);

$users = [
    ['first_name' => 'John', 'last_name' => 'Doe'],
    ['first_name' => 'Jane', 'last_name' => 'Smith'],
];

// Format full names
$fullNames = array_map(function($user) {
    return $user['first_name'] . ' ' . $user['last_name'];
}, $users);

print_r($fullNames);

?>
How it works: The `array_map` function is used to apply a callback function to each element of one or more arrays, returning a new array containing the results. This is incredibly useful for transforming data, such as converting units, formatting strings, or extracting specific properties from an array of objects/arrays, without directly modifying the original array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs