In Laravel 11.x & Laravel 12.x, the `Arr::mapWithKeys()` method is a helper function provided by Laravel `Arr` facade. It is used to transform an array by applying a callback that returns key-value pairs, creating a new associative array.
Syntax
<?php
use Illuminate\Support\Arr;
$newArray = Arr::mapWithKeys($array, function ($value, $key) {
return [$newKey => $newValue];
});
?>
Example 1: Transforming an Array
<?php
use Illuminate\Support\Arr;
$data = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
];
$result = Arr::mapWithKeys($data, function ($item) {
return [$item['id'] => $item['name']];
});
print_r($result);
?>
Output:-
<?php [ 1 => "Alice", 2 => "Bob" ] ?>Explanation: The function transforms each item into a key-value pair where the `id` is the key, and `name` is the value.
Example 2: Modify and Remap Keys
<?php
use Illuminate\Support\Arr;
$data = [
'first' => 'John',
'last' => 'Doe'
];
$result = Arr::mapWithKeys($data, function ($value, $key) {
return ["user_{$key}" => strtoupper($value)];
});
print_r($result);
?>
Output:
<?php [ "user_first" => "JOHN", "user_last" => "DOE" ] ?>Explanation: The keys are prefixed with `user_`, and values are converted to uppercase.
Example 3: Filtering & Restructuring an Array
<?php
use Illuminate\Support\Arr;
$data = [
'apple' => 50,
'banana' => 20,
'grape' => 30,
];
$result = Arr::mapWithKeys($data, function ($price, $fruit) {
return [$fruit => $price * 2]; // Double the price
});
print_r($result);
?>
Output:-
<?php [ "apple" => 100, "banana" => 40, "grape" => 60 ] ?>Explanation: Each price is doubled while keeping the same keys. Conclusion: 1. `Arr::mapWithKeys()` is a powerful helper for transforming associative arrays. 2. The callback must return an array with one key-value pair. 3. Useful for restructuring data, renaming keys, and mapping API responses.