DEV Community

Youn
Youn

Posted on

PHP array_map() Function: Concepts and Practical Examples

😄 This post is based on the content from coding.courses.

Definition and Usage

(PHP Version | 4.0.6+)

The array_map() function applies a given callback function to each element of an array and returns a new array.
The original array remains unchanged during this process.

The callback function passed to the array_map() function transforms each element and returns a new array with these transformed values.
This process is called "mapping", which is why the function is named array_map() — it maps original values to new ones.
Mapping refers to the process of associating one value with another.
This concept is used in various fields such as mathematics, computer science, and geographic information systems (GIS).

Why Use the array_map() Function?

The array_map() function is used to transform each element in an existing array according to a specific rule or logic defined in the callback function, and then creates a new array composed of the transformed elements.

  • Creating a new array of squared values from a number array
  • Converting all strings in an array to lowercase
  • Extracting specific properties from an array of objects
  • Transforming an array into UI components

Simple Example to Understand the Concept

The following example demonstrates how to use the array_map() function to create a new array by doubling each number in a numeric array.

// Define an array of numbers
$numbers = [1, 2, 3, 4, 5];

// Callback function to double each element
function double($number) {
    return $number * 2;
}

// Use array_map() to apply the callback to each element and create a new array
$doubled_numbers = array_map('double', $numbers);

print_r($doubled_numbers);
// Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
Enter fullscreen mode Exit fullscreen mode

In this example, a callback function named double() is defined to multiply each element in the $numbers array by two. The array_map() function applies this callback to every element in $numbers, producing a new array $doubled_numbers. As a result, the $doubled_numbers array contains values that are double those of the original array.

Syntax

array_map(?callable $callback, array $array, array ...$arrays): array
Enter fullscreen mode Exit fullscreen mode

Parameters

# $callback

A callback function to be applied to each element of the array(s). This function processes or transforms each element and must accept a single element as an argument, returning the transformed result. When passing the callback by name, provide it as a string.

# $array

The first array to which the $callback will be applied.

# $arrays

Additional arrays to which the $callback will be applied. The ... notation indicates that you can pass multiple arrays as separate arguments.

Return Values

Applies the callback function to each value of the given array (or arrays) and returns a new array containing the results. This new array preserves the keys of the array(s) the callback was applied to. However, there are some important details to note:

  • If only one array is passed to the callback function: The returned array preserves the keys of the original array. If the callback returns null, the original array is returned unchanged.
  • If multiple arrays are passed to the callback function: The returned array uses consecutive integer keys.
  • If any of the arrays passed to the callback are reference variables: Since PHP 8.0.0, this triggers an E_WARNING.

# If Only One Array Is Passed to the Callback Function

// Define an array of numbers
$numbers = [1, 2, 3, 4, 5];

// Callback function to double each element
function double($number) {
    return $number * 2;
}

// Apply the callback function to only one array using array_map()
$doubledNumbers = array_map('double', $numbers);

print_r($doubledNumbers);
/* Output:
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
*/
Enter fullscreen mode Exit fullscreen mode

In this example, the callback function double is applied only to the $numbers array. Since array_map() is called with a single array, the returned array preserves the keys of the original array. The output shows each element doubled while retaining the original keys.

# If Multiple Arrays Are Passed to the Callback Function

// When Arrays Passed to the Callback Have the Same Length

$array1 = [1, 2, 3];
$array2 = [4, 5, 6];

// Callback function to add corresponding elements of two arrays
function add_arrays($a, $b) {
    return $a + $b;
}

$result = array_map('add_arrays', $array1, $array2);

print_r($result);
/* Output:
Array
(
    [0] => 5
    [1] => 7
    [2] => 9
)
*/
Enter fullscreen mode Exit fullscreen mode

In this example, two arrays, $array1 and $array2, are passed to the callback function add_arrays. This function returns the sum of the values from both arrays at each position. Note that the returned array uses consecutive integer keys.

// When Arrays Passed to the Callback Have Different Lengths

$array1 = [1, 2, 3];
$array2 = [4, 5];

// Callback function to add corresponding elements of two arrays
function add_arrays($a, $b) {
    return $a + $b;
}

$result = array_map('add_arrays', $array1, $array2);

print_r($result);
/* Output:
Array
(
    [0] => 5
    [1] => 7
    [2] => 3
)
*/
Enter fullscreen mode Exit fullscreen mode

Here, $array1 and $array2 have different lengths.
array_map() applies the callback based on the length of the longest array, so the returned array matches that length. Positions where the shorter array lacks elements are filled with null. As a result, the returned array uses consecutive integer keys matching the longest input array.

Practical Examples

# Converting to Lowercase

<pre><code class="language-php">
$words = ['Hello', 'World', 'PHP', 'ARRAY'];

// Callback function to convert each string element to lowercase
function to_lowercase($word) {
    return strtolower($word);
}

// Use array_map() to apply the callback to each string element and create a new array
$lowercase_words = array_map('to_lowercase', $words);

print_r($lowercase_words);

// Output: Array ( [0] => hello [1] => world [2] => php [3] => array )
Enter fullscreen mode Exit fullscreen mode

# Handling Multiple Arrays

$names = ['John', 'Jane', 'Bob'];
$scores = [85, 92, 78];

// Create an associative array by combining names and scores
$students = array_map(function($name, $score) {
    return ['name' => $name, 'score' => $score];
}, $names, $scores);

print_r($students);

/* Output:
Array
(
    [0] => Array ( [name] => John [score] => 85 )
    [1] => Array ( [name] => Jane [score] => 92 )
    [2] => Array ( [name] => Bob [score] => 78 )
)
*/
Enter fullscreen mode Exit fullscreen mode

# Transforming Arrays of Objects

class User {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function getGreeting() {
        return "Hello, my name is " . $this->name;
    }
}

$users = [new User('Alice'), new User('Bob'), new User('Charlie')];

// Extract greetings from each user object
$greetings = array_map(function($user) {
    return $user->getGreeting();
}, $users);

print_r($greetings);

/* Output:
Array
(
    [0] => Hello, my name is Alice
    [1] => Hello, my name is Bob
    [2] => Hello, my name is Charlie
)
*/
Enter fullscreen mode Exit fullscreen mode

References

PHP array_map() Function: Concepts and Practical Examples – codingCourses

The array_map() function applies the given callback function to each element of an array and returns a new array. The original array remains unchanged.

favicon coding.courses

Top comments (0)