Content · Programming · PHP

PHP array_map() Function: Usage and Examples

Learn how to use PHP array_map() to transform array values, apply callback functions, process multiple arrays, and work with practical examples.

2 views Published Oct 16, 2026 Updated Oct 16, 2026 Admin

When working with PHP arrays, you may need to modify every element in the same way. For example, you might want to convert names to uppercase, calculate discounted prices, or format values for display.

The array_map() function lets you transform array elements using a callback function without writing a separate loop.

In this guide, you'll learn how to use array_map(), process multiple arrays, and understand how it handles array keys.

What Is array_map() in PHP?

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

Its syntax is:

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

The parameters are:

  • $callback — The function used to transform each element.
  • $array — The array containing the values to process.
  • ...$arrays — Optional additional arrays to process together.

The callback receives array values, performs an operation, and returns a result for each position.

The original arrays remain unchanged.

Example 1: Transforming Numeric Values

Let's multiply every number in an array by two.

<?php

$numbers = [5, 10, 15, 20];

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

print_r($doubled);

Output:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)

The callback is an arrow function that multiplies each value by two.

PHP 7.4 introduced arrow functions, but array_map() itself has been available since PHP 4. You can also use regular functions or anonymous functions as callbacks.

Example 2: Transforming Associative Arrays

When you pass exactly one array, array_map() preserves its original keys.

<?php

$users = [
    "admin" => "alex",
    "editor" => "taylor"
];

$result = array_map(
    "strtoupper",
    $users
);

print_r($result);

Output:

Array
(
    [admin] => ALEX
    [editor] => TAYLOR
)

The built-in strtoupper() function converts each string value to uppercase.

Notice that the keys admin and editor remain unchanged.

Important: The callback receives values, not keys. If you need to transform array keys, consider array_change_key_case() or build a new associative array.

Example 3: Processing Multiple Arrays

You can pass multiple arrays to array_map(). The callback receives corresponding values from each array.

<?php

$products = ["Keyboard", "Mouse", "Monitor"];
$prices = [50, 25, 200];

$labels = array_map(
    fn(string $name, int $price): string =>
        $name . " - $" . $price,
    $products,
    $prices
);

print_r($labels);

Output:

Array
(
    [0] => Keyboard - $50
    [1] => Mouse - $25
    [2] => Monitor - $200
)

The first product is paired with the first price, the second product with the second price, and so on.

When multiple arrays are supplied, the resulting array uses sequential integer keys, even if the original arrays have associative keys.

If the arrays have different lengths, PHP supplies null for missing positions in shorter arrays. A typed callback must be able to accept those missing values, or a TypeError may occur.

Combining Arrays with a null Callback

Passing null as the callback lets you combine corresponding array elements into smaller arrays. This is sometimes called a zip operation.

<?php

$names = ["Alex", "Taylor"];
$scores = [85, 92];

$result = array_map(null, $names, $scores);

print_r($result);

Output:

Array
(
    [0] => Array
        (
            [0] => Alex
            [1] => 85
        )

    [1] => Array
        (
            [0] => Taylor
            [1] => 92
        )
)

With only one array and a null callback, array_map() returns the input array unchanged.

Practical Example: Applying Product Discounts

Imagine you're building an online store. You have a list of products and want to apply a 10% discount to every product while keeping its other details.

Create a file named discount-products.php:

<?php

declare(strict_types=1);

$products = [
    [
        "name" => "Keyboard",
        "price" => 50.00
    ],
    [
        "name" => "Mouse",
        "price" => 25.00
    ],
    [
        "name" => "Monitor",
        "price" => 200.00
    ]
];

// Apply a 10% discount.

$discountedProducts = array_map(
    static function (array $product): array {

        $product["price"] = round(
            $product["price"] * 0.90,
            2
        );

        return $product;
    },
    $products
);

// Display discounted products.

echo "<h2>Discounted Products</h2>";
echo "<ul>";

foreach ($discountedProducts as $product) {

    $message = $product["name"]
        . " - $"
        . number_format($product["price"], 2);

    echo "<li>" . htmlspecialchars(
        $message,
        ENT_QUOTES,
        "UTF-8"
    ) . "</li>";
}

echo "</ul>";

Browser output:

Discounted Products

Keyboard - $45.00
Mouse - $22.50
Monitor - $180.00

The callback receives each product, updates its price, and returns the transformed record.

The original $products array remains unchanged. This example uses predefined, validated prices; production financial applications should use an appropriate monetary representation rather than relying on floating-point arithmetic alone.

array_map() vs array_filter() vs foreach

Approach Purpose
array_map() Transforms each element and returns a new array.
array_filter() Keeps only elements that satisfy a condition.
array_walk() Executes a callback for each element, typically for operations on the existing array.
foreach Provides flexible control over processing, modifying, or skipping elements.

Use array_map() when every element needs a transformation. It does not automatically remove elements; use array_filter() when your goal is to select or exclude values.

Common Mistakes

  • Expecting the original array to change: Use the returned array to access transformed values.
  • Expecting associative keys in the callback: The callback receives array values, not their keys.
  • Assuming keys are always preserved: Keys are preserved only when exactly one input array is supplied.
  • Ignoring different array lengths: Missing positions in shorter arrays are passed as null.
  • Expecting recursive transformation: Nested arrays must be processed explicitly when deeper transformations are required.

Key Takeaways

  • array_map() applies a callback to array elements and returns a new array.
  • It supports built-in functions, arrow functions, and anonymous callbacks.
  • Original keys are preserved when processing exactly one array.
  • Multiple arrays can be processed together by matching their positions.
  • A null callback can combine multiple arrays into grouped elements.
  • Use array_filter() when you need to remove elements rather than transform them.

The array_map() function is a useful way to transform PHP arrays while keeping code readable. It works especially well for formatting values, updating structured records, and applying consistent calculations to collections.

For additional details, see the official PHP array_map() documentation.

Share this resourceSend this page to someone who may find it useful.