PHP Functions Reference

PHP array_map() Function: Transform Array Values

Learn how array_map() applies a callback to each array element and returns a transformed array.

PHP array_map() Function

array_map() applies a callback to each element of one or more arrays and returns the resulting array.

Basic Example

$numbers = [1, 2, 3, 4];

$squared = array_map(
    fn (int $number): int => $number * $number,
    $numbers
);

The result contains the transformed values in the corresponding order.

Transform Strings

$names = ["ava", "noah", "mia"];

$labels = array_map(
    fn (string $name): string => ucfirst($name),
    $names
);

Use transformations that are predictable and do not rely on hidden external state.

Multiple Arrays

A callback can receive values from multiple arrays. When arrays have different lengths, PHP pads missing values with null for the callback arguments. Make sure the callback handles this behavior when using multiple inputs.

Preserve or Rebuild Keys

For a single input array, array_map() preserves string keys. When multiple arrays are supplied, the result uses sequential integer keys. If you need a specific key structure, consider a foreach loop.

Summary

array_map() is useful for transforming each element of a collection. Choose it when the transformation is clear and keep key behavior in mind.

Share this page Help other developers discover this resource.