Using array_map() to Apply a Callback Function to Array Elements
array_map() in PHP applies a user‑defined callback to each element of one or more arrays, returning a new array of the transformed values; the article explains its syntax, parameter requirements, return behavior, and provides multiple code examples demonstrating numeric, string, and mixed‑array usage.
In PHP, the array_map() function returns a new array containing the results of applying a callback function to each element of the input array(s). The number of parameters accepted by the callback must match the number of arrays passed to array_map() .
Signature
array array_map ( callable $callback , array $arr1 [, array $arr2, ...] )Parameters
$callback – The function to apply to each element.
$arr1 – The primary array whose elements are processed.
$array – Additional arrays whose elements are also passed to the callback.
Return value
Returns an array where each element is the result of the callback applied to the corresponding elements of the input array(s).
Example 1 – Numeric array
Output:
Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)Example 2 – Using an anonymous function with range()
Output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)Example 3 – Mapping multiple arrays with null as callback
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => one
[2] => uno
)
[1] => Array
(
[0] => 2
[1] => two
[2] => dos
)
[2] => Array
(
[0] => 3
[1] => three
[2] => tres
)
[3] => Array
(
[0] => 4
[1] => four
[2] => cuatro
)
[4] => Array
(
[0] => 5
[1] => five
[2] => cinco
)
)Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.