Fixes & guides

PHP array_map: keys, multiple arrays and when foreach is clearer

How array_map() treats keys, how to map with the key as well as the value, what happens with several arrays or a null callback, and when a plain foreach or array_walk() is the better choice.

On this page
  1. The basics
  2. What happens to the keys
  3. Using the key inside the callback
  4. Mapping several arrays at once
  5. array_map with null: zipping arrays
  6. Changing the array in place: array_walk()
  7. Common mistakes
  8. array_map or foreach?

array_map() runs a callback on every element and returns a new array of the results. The original is untouched. The signature puts the callback first, unlike array_filter(), which is the first thing everyone gets wrong:

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

The basics

$prices = [10, 25, 40];

$withTax = array_map(fn (int $p) => $p * 1.2, $prices);    // [12.0, 30.0, 48.0]
$upper   = array_map(strtoupper(...), ['a', 'b']);           // ['A', 'B']
$trimmed = array_map('trim', [' x ', "y\n"]);               // ['x', 'y']

Any callable works: an arrow function, a closure, a function name as a string, a first-class callable such as strtoupper(...) (PHP 8.1+), or [$object, 'method']. Arrow functions capture outer variables automatically; a classic closure needs use:

$rate = 1.2;
array_map(fn ($p) => $p * $rate, $prices);
array_map(function ($p) use ($rate) { return $p * $rate; }, $prices);

What happens to the keys

With one array, array_map() keeps the keys, string or integer:

array_map(fn ($v) => $v * 2, ['a' => 1, 'b' => 2]);   // ['a' => 2, 'b' => 4]
array_map(fn ($v) => $v * 2, [3 => 1, 7 => 2]);       // [3 => 2, 7 => 4]

With two or more arrays, the result is always a list indexed from 0, and the keys of the inputs are ignored.

Using the key inside the callback

The callback only receives values. To use the key too, pass the keys as a second array, then put the keys back with array_combine():

$config = ['host' => 'db', 'port' => 5432];

$lines = array_map(fn ($key, $value) => "$key=$value", array_keys($config), $config);
// ['host=db', 'port=5432']

$labelled = array_combine(array_keys($config), array_map(
    fn ($key, $value) => strtoupper($key) . ': ' . $value,
    array_keys($config),
    $config,
));
// ['host' => 'HOST: db', 'port' => 'PORT: 5432']

If that looks heavy, it is. A foreach that builds the result is often clearer when keys matter:

$labelled = [];
foreach ($config as $key => $value) {
    $labelled[$key] = strtoupper($key) . ': ' . $value;
}

Mapping several arrays at once

Extra arrays are walked in parallel, and the callback receives one argument per array. If the arrays differ in length, the shorter ones are padded with null:

$names  = ['Ana', 'Bilal', 'Chen'];
$scores = [91, 78];

array_map(fn ($n, $s) => "$n: " . ($s ?? 'n/a'), $names, $scores);
// ['Ana: 91', 'Bilal: 78', 'Chen: n/a']

array_map with null: zipping arrays

Pass null as the callback with several arrays and you get the arrays “zipped” into pairs:

array_map(null, ['a', 'b'], [1, 2]);   // [['a', 1], ['b', 2]]

With a single array, a null callback returns the array unchanged.

Changing the array in place: array_walk()

array_map() cannot modify the original or reach it by reference. array_walk() can, and its callback receives the key as the second argument:

array_walk($config, function (&$value, string $key) {
    $value = "$key=$value";
});

array_walk() returns true, not the array, so do not assign its result. For nested arrays, array_walk_recursive() visits every leaf.

Common mistakes

  • Arguments in the wrong order. array_map($array, $fn) throws a TypeError. The callback comes first in array_map(), last in array_filter() and usort().
  • Expecting it to filter. Returning null from the callback keeps a null element. Filter first with array_filter, then map.
  • Built-ins with extra parameters. array_map('round', $values) calls round($value) only; to pass a precision, write fn ($v) => round($v, 2).
  • Side effects. If the callback writes to a database or echoes output, use foreach. array_map() says “transform”, and readers expect no side effects.

array_map or foreach?

Use array_map() for a one-line transformation of every value, where the result has the same length and keys as the input. Use foreach when you need the key, want to skip items, build a differently shaped result, stop early or produce side effects. Performance is rarely a reason to choose: on PHP 8, foreach is usually a little faster, but both handle hundreds of thousands of elements in milliseconds.

To turn the mapped result into a string, see PHP array to string. To order it, see PHP sort array.

Found a mistake or something out of date? Tell us and we will fix it. See our editorial policy.

A good place to start

What are you working on?

Tools, guides, PHP versions and the archive.

ToolJSON ↔ PHP arrayConvert JSON to a PHP array literal with short or array() syntax, or turn a PHP array back into JSON. Runs in your browser; nothing is uploaded.ToolSerialize / unserializeRead PHP serialized strings as a tree, repair wrong string lengths after a search-and-replace, or serialize a PHP array or JSON. Parsed safely in your browser.ToolComposer constraint testerSee exactly which versions a Composer constraint such as ^2.1, ~1.4 or >=8.1 <8.4 allows, in plain English, and test versions against it.ToolPHP date() format builderBuild a PHP date() or DateTime::format() string with a live preview in any time zone, plus a reference for every format character.ToolBcrypt generatorGenerate a bcrypt hash with a cost slider and verify a password against an existing hash. Output matches PHP password_hash() and password_verify(). Runs in your browser.ToolPHP version checkerPaste PHP code and see the minimum version it needs, the line that decided it, and any removed functions that cap the newest version it can run on.ToolCrontab generatorBuild a cron expression with presets, read it in plain English, see the next run times, and copy the crontab line or the matching Laravel scheduler call.ToolPHP upgrade checklistPick your current and target PHP versions and get every breaking change, deprecation and tooling step in between, as a checklist you can copy.GuideAllowed memory size exhaustedWhat PHP's memory_limit fatal error means, how to tell a real leak from a big job, and fixes for the usual causes: loading whole tables, unbounded arrays, Composer and recursion.GuideComposer dependency conflictsA step-by-step way to read Composer's conflict output, find the package that is blocking you, and fix it without --ignore-platform-reqs or deleting the lock file.Guidecomposer install vs updatecomposer install reproduces composer.lock; composer update rewrites it. Here is what each command does, when to use which, and a safe production deploy routine.GuideComposer uses the wrong PHP versionComposer says "your php version (8.1.x) does not satisfy that requirement" when your server runs 8.3? The cause is usually the CLI binary, config.platform.php, or platform_check.php.GuideEloquent N+1 queriesHow to spot N+1 queries in Laravel, fix them with eager loading, withCount() and constrained loads, and make Laravel throw an exception the next time one slips in.GuideHeaders already sentThe warning names the file and line that produced output. Here is how to read it, the five usual culprits (BOM, whitespace, echo, warnings, closing tags) and fixes that do not just hide it.GuideWriting a talk proposalWhat reviewers look for in a call-for-papers submission: a specific title, an abstract for attendees, notes for the committee, and a talk-sized idea. With a worked example and a checklist.GuideLaravel queue jobs not runningJobs dispatched but never processed, stuck in the jobs table, or running old code? Work through the connection, the queue name, the worker, failed jobs and deploy restarts.PHP versionsWhat's new in PHP 8.4PHP 8.4 (released 21 November 2024) brought property hooks, public private(set) visibility, new without parentheses, lazy objects, an HTML5 DOM parser and array_find(). Plus the deprecations that matter.PHP versionsWhat's new in PHP 8.5PHP 8.5 (released 20 November 2025) added the |> pipe operator, a standards-compliant URI extension, clone() with property overrides, #[\NoDiscard] and array_first()/array_last().PHP versionsWhat's new in PHP 8.6PHP 8.6 was released on 19 November 2026. Partial function application, clamp(), readonly property defaults, Io\Poll and Time\Duration, plus the session and ValueError changes to check before upgrading.GuidePHP array_filterHow array_filter() decides what to keep, why it removes "0" without a callback, how to filter by key or by key and value, and why the result needs array_values() before you treat it as a list.GuidePHP array_mapHow array_map() treats keys, how to map with the key as well as the value, what happens with several arrays or a null callback, and when a plain foreach or array_walk() is the better choice.GuidePHP array to JSONWhy json_encode() sometimes gives you an object instead of a list, how to keep floats and slashes intact, and how to catch the silent false that malformed UTF-8 returns.GuidePHP array to stringThree ways to turn a PHP array into a string, and when to use each: implode() for display and CSV-like lists, json_encode() for APIs and storage, serialize() for PHP-only data. Plus the Array to string conversion warning.GuidePHP FibersPHP 8.1 Fibers let a function pause and resume without returning. Here is how start, suspend and resume pass values, how Fibers differ from generators and threads, and where they help in real code.GuidePHP in_arrayWhy in_array() can return true for values that are not in the array, what changed in PHP 8, when to pass strict = true, and how to replace slow in_array() calls with isset() lookups.GuideInterface vs abstract classInterfaces define what a class can do; abstract classes share how it is done. A side-by-side table, examples of each, the common pattern of using both, and what PHP 8.1 to 8.4 changed for interfaces.GuidePHP sort arrayWhich PHP sort function to use, in one table: by value or key, keep keys or not, ascending or descending, or with your own comparison. Plus sorting by a column, by several fields and naturally.GuideDuplicate webhooks in PHPWebhook providers retry, so the same event can arrive twice. Verify the signature, record the event ID with a unique key, answer fast and process in a queue: a pattern that works in plain PHP, Laravel and Symfony.GuidePHPStan baseline for legacy codeGenerate a PHPStan baseline, stop new errors from getting in, then raise the level step by step. A tested routine for old PHP codebases.GuidePSR-4 autoloadingHow PSR-4 maps namespaces to folders, how to configure it in composer.json, and why "Class not found" happens: case, typos, a stale autoloader or a namespace that does not match the path.GuideSerialized data broken after search-replaceChanging a domain name with SQL REPLACE() or sed corrupts PHP serialized strings because their byte lengths no longer match. Here is how to spot it and repair it safely.GuideUpgrade PHP with RectorUpgrade a PHP application one version at a time: pin the baseline, let Rector rewrite syntax, let PHPStan find what Rector cannot, and prove it with tests before you switch runtimes.PHP versionsSupported PHP versionsRelease, active support and end-of-life dates for every PHP version.ArchiveSunshinePHP talk archive 2013–2020Talk titles and speakers from eight years of the Miami PHP conference.ArchiveSpeaker indexEveryone who spoke at SunshinePHP, A to Z.