array_map() creates a new array by applying a function to every item of an old array. The old array is not changed.
<?php
$prices = [100, 200, 300];
$withTax = array_map(fn($price) => $price * 1.18, $prices);
echo implode(", ", $withTax);
118, 236, 354
The first argument is the function. The second is the array.
Use a built-in function
<?php
$names = [" ana ", "ben ", " cy"];
$clean = array_map("trim", $names);
echo implode("|", $clean);
ana|ben|cy
Change the shape of records
<?php
$users = [
["first" => "Ada", "last" => "Lovelace"],
["first" => "Alan", "last" => "Turing"],
];
$names = array_map(fn($u) => $u["first"] . " " . $u["last"], $users);
print_r($names);
Array
(
[0] => Ada Lovelace
[1] => Alan Turing
)
Build HTML
<?php
$tags = ["php", "web"];
$links = array_map(fn($tag) => "<a href=\"/tag/$tag\">$tag</a>", $tags);
echo implode(" ", $links);
<a href="/tag/php">php</a> <a href="/tag/web">web</a>
Keys
With one array, array_map() keeps the keys.
<?php
$prices = ["pen" => 10, "book" => 250];
print_r(array_map(fn($p) => $p * 2, $prices));
Array
(
[pen] => 20
[book] => 500
)
If you need the key inside the function, use array_keys() as a second array, or a foreach.
<?php
$prices = ["pen" => 10, "book" => 250];
$lines = array_map(fn($name, $price) => "$name costs $price", array_keys($prices), $prices);
print_r($lines);
Array
(
[0] => pen costs 10
[1] => book costs 250
)
Two arrays at once
<?php
$a = [1, 2, 3];
$b = [10, 20, 30];
print_r(array_map(fn($x, $y) => $x + $y, $a, $b));
Array
(
[0] => 11
[1] => 22
[2] => 33
)
map vs foreach
array_map | foreach | |
|---|---|---|
| Result | A new array | Whatever you build |
| Changes the original | No | Only if you write to it |
| Best for | Transforming each item | Doing 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.
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.