0
0
PhpHow-ToBeginner · 3 min read

How to Use array_map in PHP: Syntax and Examples

In PHP, array_map applies a callback function to each element of one or more arrays and returns a new array with the results. You pass the callback as the first argument and the array(s) to transform as the following arguments.
📐

Syntax

The array_map function takes a callback function and one or more arrays. It applies the callback to each element of the arrays and returns a new array with the transformed values.

  • callback: A function to apply to each element.
  • array1, array2, ...: One or more arrays to process.
php
array array_map ( callable $callback , array $array1 [, array ...$arrays ] )
💻

Example

This example shows how to use array_map to square each number in an array.

php
<?php
$numbers = [1, 2, 3, 4, 5];
$squares = array_map(fn($n) => $n * $n, $numbers);
print_r($squares);
?>
Output
Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
⚠️

Common Pitfalls

Common mistakes include:

  • Passing a non-callable as the first argument, which causes an error.
  • Using array_map with multiple arrays of different lengths, which processes only up to the shortest array length.
  • Not returning a value from the callback, resulting in null elements.
php
<?php
// Wrong: callback missing
// $result = array_map('not_a_function', [1, 2, 3]); // Fatal error

// Right: callback returns value
$result = array_map(fn($x) => $x + 1, [1, 2, 3]);
print_r($result);

// Multiple arrays of different lengths
$a = [1, 2, 3];
$b = [4, 5];
$sum = array_map(fn($x, $y) => $x + $y, $a, $b);
print_r($sum);
?>
Output
Array ( [0] => 2 [1] => 3 [2] => 4 ) Array ( [0] => 5 [1] => 7 )
📊

Quick Reference

ParameterDescription
callbackFunction applied to each element
array1First array to process
array2, ...Optional additional arrays to process in parallel
ReturnNew array with callback results

Key Takeaways

Use array_map to apply a function to each element of one or more arrays and get a new array.
The callback must return a value; otherwise, the result will contain nulls.
When using multiple arrays, array_map stops at the shortest array length.
Always pass a valid callable as the first argument to avoid errors.
array_map is useful for transforming arrays without writing loops.