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.
This function is commonly used in scenarios such as:
- 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
Let's explain with a simple example. 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 )
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
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
)
*/
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
$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
)
*/
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.
$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
)
*/
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.
If Any of the Arrays Passed to the Callback Are Reference Variables
$array = [1, 2, 3];
// Callback function expects a reference, but array elements are not passed by reference
function addOne(&$value) {
$value += 1;
}
array_map('addOne', $array);
Practical Examples
Here are three practical use cases demonstrating how to use array_map()
to transform each element of an array and return a new array.
Converting to Lowercase
You can use array_map()
to create a new array by converting each string in an array 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 )
In the code above, the callback function to_lowercase
is defined and applied to the $words
array via array_map()
. Each string element in the array is converted to lowercase using the strtolower()
function, resulting in a new array containing all lowercase strings.
Handling Multiple Arrays
This use case involves manipulating and combining multiple arrays simultaneously. For example, you can sum values from multiple arrays or combine them into new data structures.
$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 )
)
*/
Transforming Arrays of Objects
You can use array_map()
to extract specific properties or call methods on objects in an array. For instance, extracting names from an array of user objects or calling a method on each object to generate new data.
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
)
*/
array_map()
is a powerful tool for array manipulation and transformation, useful in a variety of scenarios.