PHP array_map: keys, multiple arrays and when foreach is clearer
How array_map() treats keys, how to map with the key as well as the value, what happens with several arrays or a null callback, and when a plain foreach or array_walk() is the better choice.
On this page
array_map() runs a callback on every element and returns a new array of the results. The original is untouched. The signature puts the callback first, unlike array_filter(), which is the first thing everyone gets wrong:
array_map(?callable $callback, array $array, array ...$arrays): array
The basics
$prices = [10, 25, 40];
$withTax = array_map(fn (int $p) => $p * 1.2, $prices); // [12.0, 30.0, 48.0]
$upper = array_map(strtoupper(...), ['a', 'b']); // ['A', 'B']
$trimmed = array_map('trim', [' x ', "y\n"]); // ['x', 'y']
Any callable works: an arrow function, a closure, a function name as a string, a first-class callable such as strtoupper(...) (PHP 8.1+), or [$object, 'method']. Arrow functions capture outer variables automatically; a classic closure needs use:
$rate = 1.2;
array_map(fn ($p) => $p * $rate, $prices);
array_map(function ($p) use ($rate) { return $p * $rate; }, $prices);
What happens to the keys
With one array, array_map() keeps the keys, string or integer:
array_map(fn ($v) => $v * 2, ['a' => 1, 'b' => 2]); // ['a' => 2, 'b' => 4]
array_map(fn ($v) => $v * 2, [3 => 1, 7 => 2]); // [3 => 2, 7 => 4]
With two or more arrays, the result is always a list indexed from 0, and the keys of the inputs are ignored.
Using the key inside the callback
The callback only receives values. To use the key too, pass the keys as a second array, then put the keys back with array_combine():
$config = ['host' => 'db', 'port' => 5432];
$lines = array_map(fn ($key, $value) => "$key=$value", array_keys($config), $config);
// ['host=db', 'port=5432']
$labelled = array_combine(array_keys($config), array_map(
fn ($key, $value) => strtoupper($key) . ': ' . $value,
array_keys($config),
$config,
));
// ['host' => 'HOST: db', 'port' => 'PORT: 5432']
If that looks heavy, it is. A foreach that builds the result is often clearer when keys matter:
$labelled = [];
foreach ($config as $key => $value) {
$labelled[$key] = strtoupper($key) . ': ' . $value;
}
Mapping several arrays at once
Extra arrays are walked in parallel, and the callback receives one argument per array. If the arrays differ in length, the shorter ones are padded with null:
$names = ['Ana', 'Bilal', 'Chen'];
$scores = [91, 78];
array_map(fn ($n, $s) => "$n: " . ($s ?? 'n/a'), $names, $scores);
// ['Ana: 91', 'Bilal: 78', 'Chen: n/a']
array_map with null: zipping arrays
Pass null as the callback with several arrays and you get the arrays “zipped” into pairs:
array_map(null, ['a', 'b'], [1, 2]); // [['a', 1], ['b', 2]]
With a single array, a null callback returns the array unchanged.
Changing the array in place: array_walk()
array_map() cannot modify the original or reach it by reference. array_walk() can, and its callback receives the key as the second argument:
array_walk($config, function (&$value, string $key) {
$value = "$key=$value";
});
array_walk() returns true, not the array, so do not assign its result. For nested arrays, array_walk_recursive() visits every leaf.
Common mistakes
- Arguments in the wrong order.
array_map($array, $fn)throws aTypeError. The callback comes first inarray_map(), last inarray_filter()andusort(). - Expecting it to filter. Returning
nullfrom the callback keeps anullelement. Filter first with array_filter, then map. - Built-ins with extra parameters.
array_map('round', $values)callsround($value)only; to pass a precision, writefn ($v) => round($v, 2). - Side effects. If the callback writes to a database or echoes output, use
foreach.array_map()says “transform”, and readers expect no side effects.
array_map or foreach?
Use array_map() for a one-line transformation of every value, where the result has the same length and keys as the input. Use foreach when you need the key, want to skip items, build a differently shaped result, stop early or produce side effects. Performance is rarely a reason to choose: on PHP 8, foreach is usually a little faster, but both handle hundreds of thousands of elements in milliseconds.
To turn the mapped result into a string, see PHP array to string. To order it, see PHP sort array.