PHP 8 reference · Array Functions
PHP array_map() Function
Apply a callback to every element of one or more arrays and return a new array of the results.
PHP 8 Since 4.0
Syntax
array_map(?callable $callback, array $array, array ...$arrays): array
Parameters
| Parameter | Description |
|---|---|
callback |
A function that receives each value (one argument per array); null zips the arrays together. |
array |
The input array. |
arrays optional |
More arrays to walk in parallel. |
Return value
A new array of the callback's results.
Examples
<?php
$prices = [10, 25, 40];
print_r(array_map(fn($p) => $p * 1.2, $prices));
Output
Array
(
[0] => 12
[1] => 30
[2] => 48
)<?php
print_r(array_map("strtoupper", ["php", "sql"]));
print_r(array_map(fn($name, $age) => "$name ($age)", ["Ada", "Alan"], [36, 41]));
Output
Array
(
[0] => PHP
[1] => SQL
)
Array
(
[0] => Ada (36)
[1] => Alan (41)
)<?php
$users = ["u1" => "ada", "u2" => "alan"];
print_r(array_map("ucfirst", $users)); // string keys are kept with one array
Output
Array
(
[u1] => Ada
[u2] => Alan
)Common mistakes
- The callback comes first in
array_map()but second inarray_filter()andarray_reduce(). - The callback only gets values. For keys, map over
array_keys($a)or pass both arrays:array_map(fn($k, $v) => …, array_keys($a), $a).
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
map()· Pythonarray.map()· JavaScript
Related
array_filter()· Keep only the elements for which a callback returns true. Without a callback it removes empty values; keys are kept.array_reduce()· Reduce an array to a single value by passing a running total and each element to a callback.array_walk()· Run a callback on every element of an array, with the value and key. Take the value by reference to change it in place.array_column()· Return the values from one column of a list of records, optionally keyed by another column.- PHP Array Functions · tutorial
- PHP Arrays · tutorial