array_map
Applies a function to every element of an array.
Available since: PHP 4
Syntax
array_map(?callable $callback, array $array, array ...$arrays): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $callback | ?callable | A function that receives an element and returns the new value. |
| $array | array | The source array. |
| ...$arrays | array | Extra 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, JSNotes
The source array is not modified — a new one is returned. To select some elements rather than transform them, use array_filter().
See also
- array_filter — Keeps the array elements that pass a test.
Related recipes
In the tutorial
- Functions — How to declare and call functions in PHP — parameters, return values, types and scope.