array_map() returns an array containing
the results of applying the callback
to the corresponding value of array
(and arrays if more arrays are provided)
used as arguments for the callback.
The number of parameters that the callback
function accepts should match the number of arrays
passed to array_map(). Excess
input arrays are ignored. An ArgumentCountError
is thrown if an insufficient number of arguments is provided.
null can be passed as a value to callback
to perform a zip operation on multiple arrays and return an array
where each element is an array containing the elements from the input arrays at the
same position of the internal array pointer (see example below).
If only array is provided,
array_map() will return the input array.
array
An array to run through the callback function.
arrays
Supplementary variable list of array arguments to run through the
callback function.
Return Values
Returns an array containing the results of applying the callback
function to the corresponding value of array
(and arrays if more arrays are provided)
used as arguments for the callback.
The returned array will preserve the keys of the array argument if and only
if exactly one array is passed. If more than one array is passed, the
returned array will have sequential integer keys.
Changelog
Version
Description
8.0.0
If callback expects a parameter to be passed
by reference, this function will now emit an E_WARNING.
<?php
function show_Spanish(int $n, string $m): string
{
return "The number {$n} is called {$m} in Spanish";
}
function map_Spanish(int $n, string $m): array
{
return [$n => $m];
}
$a = [1, 2, 3, 4, 5];
$b = ['uno', 'dos', 'tres', 'cuatro', 'cinco'];
$c = array_map('show_Spanish', $a, $b);
print_r($c);
$d = array_map('map_Spanish', $a , $b);
print_r($d);
?>
The above example will output:
// printout of $c
Array
(
[0] => The number 1 is called uno in Spanish
[1] => The number 2 is called dos in Spanish
[2] => The number 3 is called tres in Spanish
[3] => The number 4 is called cuatro in Spanish
[4] => The number 5 is called cinco in Spanish
)
// printout of $d
Array
(
[0] => Array
(
[1] => uno
)
[1] => Array
(
[2] => dos
)
[2] => Array
(
[3] => tres
)
[3] => Array
(
[4] => cuatro
)
[4] => Array
(
[5] => cinco
)
)
Usually when using two or more arrays, they should be of equal length
because the callback function is applied in parallel to the corresponding
elements.
If the arrays are of unequal length, shorter ones will be extended with empty
elements to match the length of the longest.
An interesting use of this function is to construct an array of arrays,
which can be easily performed by using null
as the name of the callback function