The Arr::map() Helper
Apply a callback to every element in an array (including nested arrays) without converting to a Collection first.
Overview
Arr::map() applies a callback to each value of a plain PHP array, returning a new array with the results. Unlike array_map(), it passes both the value and the key to your callback, and it preserves the original keys.
Usage
use Illuminate\Support\Arr;
$data = ['first' => 'taylor', 'last' => 'otwell'];
Arr::map($data, fn ($value, $key) => strtoupper($value));
// ['first' => 'TAYLOR', 'last' => 'OTWELL']
It recursively maps nested arrays too:
$config = [
'database' => [
'host' => 'localhost',
'port' => '3306',
],
'cache' => [
'driver' => 'redis',
],
];
Arr::map($config, fn ($value) => is_string($value) ? strtoupper($value) : $value);
// [
// 'database' => ['host' => 'LOCALHOST', 'port' => '3306'],
// 'cache' => ['driver' => 'REDIS'],
// ]
Compared to array_map
// PHP's array_map — no key access, numeric re-indexing risk
array_map(fn ($v) => strtoupper($v), $data);
// Arr::map — key access, preserves keys, cleaner API
Arr::map($data, fn ($value, $key) => strtoupper($value));
When to Use
- Transforming config or settings arrays without creating a Collection
- Processing associative arrays where you need access to keys
- Working with nested data structures that need recursive mapping
- When
collect()->map()feels like overkill for a simple array