Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_map

Applies a function to every element of an array.

Available since: PHP 4

Syntax

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

Parameters

ParameterTypeDescription
$callback?callableA function that receives an element and returns the new value.
$arrayarrayThe source array.
...$arraysarrayExtra arrays: their elements are passed to the function as further arguments.

Return value

arrayA new array holding the results of the function calls.

Examples

Doubling every number:

<?php
 
print_r(array_map(fn ($n) => $n * 2, [1, 2, 3]));

Output:

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)

You can pass the name of an existing function instead of your own:

<?php
 
echo implode(', ', array_map('mb_strtoupper', ['php', 'js']));

Output:

PHP, JS

Notes

The source array is not modified — a new one is returned. To select some elements rather than transform them, use array_filter().

See also

Related recipes

In the tutorial

  • Functions — How to declare and call functions in PHP — parameters, return values, types and scope.

Thanks for reading!

Donate to the site — we work hard for you.