CKTIS / PHP
array_map: transforming array values
array_map builds an array of callback results for successive values. With one input array it preserves keys; with several it creates consecutive numeric keys.
Version: PHP 8.4
Syntax
array_map(?callable $callback, array $array, array ...$arrays): arrayThe callback should return a new value. fn(int $value): int => $value * 2 doubles a number. Merely using echo in the callback prints text but does not replace returning a result. Ordinary scalar mapping does not change the source array.
With one array, string and numeric keys are preserved. With several arrays, values are paired by position in iteration order, not by matching keys. Shorter arrays are padded with null; account for this in callback types and logic.
A null callback with several arrays creates arrays of corresponding values. With one array it returns that array. The example shows key-preserving mapping and this combination of two arrays with different lengths.
array_map does not filter elements: a returned null also becomes a result value. Use array_filter to select elements. Do not treat mapping as a deep copy of objects; a callback can mutate an object passed to it or have other side effects.
Examples
<?php
declare(strict_types=1);
$values = ["a" => 2, "b" => 3];
$mapped = array_map(fn(int $value): int => $value * 2, $values);
echo json_encode($mapped, JSON_THROW_ON_ERROR), "\n";
$paired = array_map(null, [1, 2], [10]);
echo json_encode($paired, JSON_THROW_ON_ERROR), "\n";
Result
{"a":4,"b":6}
[[1,10],[2,null]]