PHP array_map() Function
Palavras-chave:
Publicado em: 06/08/2025Understanding and Utilizing PHP's array_map() Function
The array_map()
function in PHP is a powerful tool for applying a callback function to each element of one or more arrays. It returns a new array containing the results of applying the callback function to the corresponding elements of the input arrays. This article aims to provide a comprehensive understanding of array_map()
, covering its usage, complexities, and alternative approaches.
Fundamental Concepts / Prerequisites
To effectively understand array_map()
, you should have a basic understanding of the following PHP concepts:
- Arrays: Ordered, indexed collections of data.
- Functions/Callbacks: Callable units of code that can be passed as arguments to other functions.
- Closures (Anonymous Functions): Functions without a name, often used as callbacks.
Core Implementation/Solution
The array_map()
function takes a callback function as its first argument and one or more arrays as subsequent arguments. The callback function is applied to each element of the arrays, and the results are collected into a new array.
<?php
// Example 1: Squaring each element of an array
function square($n) {
return $n * $n;
}
$numbers = [1, 2, 3, 4, 5];
$squared_numbers = array_map('square', $numbers);
print_r($squared_numbers); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
// Example 2: Using an anonymous function (closure)
$numbers = [1, 2, 3, 4, 5];
$cubed_numbers = array_map(function($n) {
return $n * $n * $n;
}, $numbers);
print_r($cubed_numbers); // Output: Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )
// Example 3: Using multiple arrays (adding corresponding elements)
$numbers1 = [1, 2, 3, 4, 5];
$numbers2 = [6, 7, 8, 9, 10];
$summed_numbers = array_map(function($n1, $n2) {
return $n1 + $n2;
}, $numbers1, $numbers2);
print_r($summed_numbers); // Output: Array ( [0] => 7 [1] => 9 [2] => 11 [3] => 13 [4] => 15 )
// Example 4: Mapping to NULL - Useful for iterating and not returning anything
$emails = ['test@example.com', 'another@example.org'];
$validEmails = [];
array_map(function($email) use (&$validEmails) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$validEmails[] = $email;
}
return null; // Important to return null
}, $emails);
print_r($validEmails); // Output: Array ( [0] => test@example.com [1] => another@example.org )
?>
Code Explanation
Example 1: We define a function square()
that takes a number as input and returns its square. We then call array_map()
with 'square'
(the function name as a string) and the $numbers
array. The result, $squared_numbers
, is a new array where each element is the square of the corresponding element in $numbers
.
Example 2: This example uses an anonymous function (closure) directly within the array_map()
call. This is a common practice for simple operations, making the code more concise.
Example 3: This example demonstrates using array_map()
with multiple arrays. The callback function receives corresponding elements from each input array as arguments. The number of arguments the callback function accepts must match the number of arrays passed to array_map()
(except when mapping to NULL which can take any number).
Example 4: Sometimes you don't need to create a new array but want to operate on the elements. Returning `null` from the callback allows iterating and performing actions (like adding valid emails to a separate array, in this case, `$validEmails`) without creating a new transformed array. Note the `use (&$validEmails)` which imports the `$validEmails` variable by reference into the closure scope allowing modifications inside the callback.
Complexity Analysis
The time complexity of array_map()
is O(n), where n is the number of elements in the input array (or the number of elements in the shortest array when multiple arrays are provided). This is because the callback function is applied to each element of the array(s) once.
The space complexity is also O(n) because array_map()
creates a new array to store the results. In the worst-case scenario, the new array will have the same number of elements as the input array.
Alternative Approaches
A common alternative to array_map()
is using a foreach
loop. A foreach
loop offers more control over the iteration process and can sometimes be more readable for complex transformations. However, array_map()
can often be more concise, especially for simple operations, and might offer a performance benefit in certain cases (although this can vary depending on the specific operation and PHP version).
For example, the squaring example could be rewritten using a foreach
loop like this:
<?php
$numbers = [1, 2, 3, 4, 5];
$squared_numbers = [];
foreach ($numbers as $number) {
$squared_numbers[] = $number * $number;
}
print_r($squared_numbers);
?>
The `foreach` approach offers more control but can be slightly more verbose.
Conclusion
The array_map()
function is a valuable tool for transforming array elements in PHP. It provides a concise and efficient way to apply a callback function to each element of an array (or multiple arrays), returning a new array with the results. Understanding its usage, complexities, and alternatives allows developers to choose the most appropriate method for their specific needs. Consider using it for simple, element-wise transformations for improved code readability and potential performance benefits.