Web Analytics

PHP array_map() Function

Array Function PHP 4.0.6+

The array_map() function applies a callback function to each element of an array and returns a new array with the results.

Syntax

array_map(?callable $callback, array $array, array ...$arrays): array

Parameters

Parameter Type Description
$callback callable|null A callback function to apply to each element
$array array The array to process
$arrays array Additional arrays (optional)

Return Value

Returns a new array containing the results of applying the callback function to each element.

Try It Online

Output
Click Run to execute your code

More Examples

Using Built-in Functions

<?php
$names = ["john", "jane", "bob"];

// Capitalize all names
$capitalized = array_map('ucfirst', $names);
print_r($capitalized);
// ["John", "Jane", "Bob"]
?>

Using Arrow Functions (PHP 7.4+)

<?php
$numbers = [1, 2, 3, 4, 5];

// Square each number
$squares = array_map(fn($n) => $n * $n, $numbers);
print_r($squares);
// [1, 4, 9, 16, 25]
?>

Multiple Arrays

<?php
$first = ["John", "Jane"];
$last = ["Doe", "Smith"];

// Combine first and last names
$full = array_map(fn($f, $l) => "$f $l", $first, $last);
print_r($full);
// ["John Doe", "Jane Smith"]
?>

With null Callback (Zip Arrays)

<?php
$a = [1, 2, 3];
$b = ['a', 'b', 'c'];

$zipped = array_map(null, $a, $b);
print_r($zipped);
// [[1, 'a'], [2, 'b'], [3, 'c']]
?>
Tip: Unlike array_filter(), array_map() always returns an array with the same number of elements as the input.

Common Use Cases

  • Transforming data (e.g., formatting prices, dates)
  • Extracting values from objects/arrays
  • Applying calculations to all elements
  • Converting data types

Related Functions