Skip to content

PHP Tutorial Arrays

Array Mapping

Lesson 125 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

array_map() creates a new array by applying a function to every item of an old array. The old array is not changed.

index.php
PHP
<?php
$prices = [100, 200, 300];

$withTax = array_map(fn($price) => $price * 1.18, $prices);

echo implode(", ", $withTax);
Output
OUTPUT
118, 236, 354

The first argument is the function. The second is the array.

Use a built-in function

index.php
PHP
<?php
$names = [" ana ", "ben  ", "  cy"];

$clean = array_map("trim", $names);

echo implode("|", $clean);
Output
OUTPUT
ana|ben|cy

Change the shape of records

index.php
PHP
<?php
$users = [
    ["first" => "Ada", "last" => "Lovelace"],
    ["first" => "Alan", "last" => "Turing"],
];

$names = array_map(fn($u) => $u["first"] . " " . $u["last"], $users);

print_r($names);
Output
OUTPUT
Array
(
    [0] => Ada Lovelace
    [1] => Alan Turing
)

Build HTML

index.php
PHP
<?php
$tags = ["php", "web"];

$links = array_map(fn($tag) => "<a href=\"/tag/$tag\">$tag</a>", $tags);

echo implode(" ", $links);
Output
OUTPUT
<a href="/tag/php">php</a> <a href="/tag/web">web</a>

Keys

With one array, array_map() keeps the keys.

index.php
PHP
<?php
$prices = ["pen" => 10, "book" => 250];

print_r(array_map(fn($p) => $p * 2, $prices));
Output
OUTPUT
Array
(
    [pen] => 20
    [book] => 500
)

If you need the key inside the function, use array_keys() as a second array, or a foreach.

index.php
PHP
<?php
$prices = ["pen" => 10, "book" => 250];

$lines = array_map(fn($name, $price) => "$name costs $price", array_keys($prices), $prices);

print_r($lines);
Output
OUTPUT
Array
(
    [0] => pen costs 10
    [1] => book costs 250
)

Two arrays at once

index.php
PHP
<?php
$a = [1, 2, 3];
$b = [10, 20, 30];

print_r(array_map(fn($x, $y) => $x + $y, $a, $b));
Output
OUTPUT
Array
(
    [0] => 11
    [1] => 22
    [2] => 33
)

map vs foreach

array_mapforeach
ResultA new arrayWhatever you build
Changes the originalNoOnly if you write to it
Best forTransforming each itemDoing something with each item

If you just want to print each item or save it, a foreach says what you mean. array_map is for transformation.

lightbulb
Argument order
array_map($function, $array) takes the function first, but array_filter($array, $function) takes the array first. It is a famous inconsistency, and you simply have to remember it.