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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_map(?callable $callback, array $array, array ...$arrays): array

Parameters

ParameterDescription
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

Transform each valueTry it yourself
<?php
$prices = [10, 25, 40];
print_r(array_map(fn($p) => $p * 1.2, $prices));

Output

Array
(
    [0] => 12
    [1] => 30
    [2] => 48
)
Built-in callbacks and two arraysTry it yourself
<?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)
)
KeysTry it yourself
<?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 in array_filter() and array_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

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?