Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_map() function

Reference for PHP array_map(): apply a callback to every element, work with several arrays at once, and understand how keys are preserved or lost.

array_map() calls a function on every element of an array and returns a new array with the results. The original array is not changed. It is the standard tool for transforming each item of a list: converting types, formatting values, extracting a field.

The callback can be a closure, an arrow function, the name of a function, or any other callable. If you pass several arrays, the callback receives one element from each array per call.

PHP
<?php
$squares = array_map(fn($n) => $n * $n, [1, 2, 3]);
// [1, 4, 9]

Try it

PHP Transforming a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Several arrays and keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_map(?callable $callback, array $array, array ...$arrays): array
Name Description
$callback Called for each element. With several arrays it takes one parameter per array. May be null when you pass two or more arrays (see below).
$array The array to process.
...$arrays Optional extra arrays, processed in parallel.

Return value: a new array of the callback results.

Errors: a TypeError is thrown if the callback is not callable.

Usage notes

  • Keys with one array: the keys, including string keys, are preserved. Use array_values() afterwards if you want a clean list.
  • Keys with several arrays: the result is a list with keys 0, 1, 2, ... and the original keys are lost.
  • Unequal lengths: shorter arrays are padded with null up to the length of the longest.
  • null callback: with two or more arrays it builds an array of arrays, one per position (a "zip"). With a single array it simply returns that array.
  • No access to the key. The callback only sees values. To use keys, map over array_keys() or combine results with array_combine().
  • Not for side effects. If you only want to run code for each element, use foreach or array_walk(); array_map() builds a result array you would throw away.
  • Built-in functions work as callbacks, but those with optional extra parameters may behave oddly; an arrow function makes the call explicit.
  • Selecting a field from rows is shorter with array_column().