The array_map()
function in PHP is used to apply a callback function to each element of one or more arrays, returning a new array containing the results.
🔹 Syntax:
array_map(callback, array1, array2, ...)
- callback: A function (can be user-defined or built-in) to apply to the array elements.
- array1, array2, ...: One or more arrays. If more than one array is provided, the callback should accept that many parameters.
🔸 Example 1: Square each number in an array
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($num) {
return $num * $num;
}, $numbers);
print_r($squared);
🔹 Output:
Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)
🔸 Example 2: Using a built-in function — converting strings to uppercase
$names = ["alice", "bob", "charlie"];
$upperNames = array_map("strtoupper", $names);
print_r($upperNames);
🔹 Output:
Array
(
[0] => ALICE
[1] => BOB
[2] => CHARLIE
)
🔸 Example 3: Multiple arrays – combining first and last names
$firstNames = ["John", "Jane", "Jim"];
$lastNames = ["Doe", "Smith", "Beam"];
$fullNames = array_map(function($first, $last) {
return "$first $last";
}, $firstNames, $lastNames);
print_r($fullNames);
🔹 Output:
Array
(
[0] => John Doe
[1] => Jane Smith
[2] => Jim Beam
)
🔸 Example 4: Return null
callback (identity function)
If you pass null
as the callback, array_map()
will return the input array(s) as-is (used often when combining arrays):
$a = [1, 2, 3];
$b = ["a", "b", "c"];
$combined = array_map(null, $a, $b);
print_r($combined);
🔹 Output:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 2
[1] => b
)
[2] => Array
(
[0] => 3
[1] => c
)
)