Understanding the PHP array_map Function
This article explains the purpose, syntax, and practical usage of the
array_map() function in PHP. You will learn how this
built-in function allows you to transform array elements using custom
callback functions, how it handles multiple arrays simultaneously, and
how it compares to similar array functions through clear code
examples.
The primary purpose of the array_map() function in PHP
is to apply a callback function to every element of one or more arrays,
returning a new array containing the modified elements. It provides a
clean, declarative way to perform data transformation without writing
manual loop structures.
Syntax of array_map()
The basic syntax of the function is as follows:
array_map(?callable $callback, array $array, array ...$arrays): array$callback: The function to apply to each element of the array(s). Ifnullis passed,array_map()performs a “zip” operation, creating an array of arrays.$array: The primary array to be mapped....$arrays: Optional additional arrays to map in parallel.
Key Characteristics
- Immutability:
array_map()does not modify the original array. Instead, it generates and returns a brand-new array with the transformed values. - Preserves Keys for Single Arrays: When operating on a single array, associative string keys are preserved in the returned array. However, if multiple arrays are passed, the returned array will use sequential numeric keys.
- Parallel Processing: If multiple arrays are provided, the callback function receives elements from each array at the corresponding index.
Practical Code Examples
Example 1: Modifying a Single Array
In this example, array_map() is used with an anonymous
function to square every number in an array.
$numbers = [1, 2, 3, 4, 5];
$squaredNumbers = array_map(function($number) {
return $number * $number;
}, $numbers);
print_r($squaredNumbers);
// Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )Example 2: Mapping Multiple Arrays
You can pass multiple arrays to array_map(). The
callback function must accept parameters matching the number of arrays
passed.
$spanish = ['uno', 'dos', 'tres'];
$english = ['one', 'two', 'three'];
$translations = array_map(function($sp, $en) {
return "$sp means $en";
}, $spanish, $english);
print_r($translations);
// Output: Array ( [0] => uno means one [1] => dos means two [2] => tres means three )array_map() vs. array_walk()
While both functions iterate over arrays, they serve different
purposes: * array_map() returns a brand
new array and is ideal for pure data transformation without altering the
source data. * array_walk() runs a
callback on the original array in-place and returns a boolean. It is
typically used when you need to modify the original array directly or
perform actions based on array values rather than returning a new
dataset.