Using Arr::map() in Laravel 11.x & Laravel 12.x

In Laravel 11.x & Laravel 12.x, the `Arr::map()` method is a powerful utility provided by the `Illuminate\Support\Arr` class. It allows you to apply a callback function to each element of an array and transform the array’s values. This is particularly useful when you need to modify or process array data without writing loops manually.

What is `Arr::map()`?

The `Arr::map()` method applies a callback function to each element of an array and returns a new array with the transformed values. It works similarly to PHP’s native `array_map()` function but is integrated into Laravel’s `Arr` utility class.

Syntax

<?php
Arr::map(array $array, callable $callback): array
?>

->`$array`: The input array to be processed.
->`$callback`: A callable function that takes the array’s value and key as arguments and returns the transformed value.

1. Basic Transformation

Transform each value in an array by appending a string:

<?php
use Illuminate\Support\Arr;

$array = ['apple', 'banana', 'cherry'];
$result = Arr::map($array, function ($value, $key) {
return "fruit: $value";
});

print_r($result);
?>

Output:

<?php
Array
(
[0] => fruit: apple
[1] => fruit: banana
[2] => fruit: cherry
)
?>

2. Using Keys in the Callback

You can also use the array keys in the callback function:

<?php
use Illuminate\Support\Arr;

$array = ['a' => 1, 'b' => 2, 'c' => 3];
$result = Arr::map($array, function ($value, $key) {
return "$key: $value";
});

print_r($result);
?>

Output:

<?php
Array
(
[a] => a: 1
[b] => b: 2
[c] => c: 3
)
?>

3. Transforming Associative Arrays

Modify values in an associative array:

<?php
use Illuminate\Support\Arr;

$array = [
'name' => 'John',
'age' => 30,
'city' => 'New York',
];

$result = Arr::map($array, function ($value, $key) {
return strtoupper($value);
});

print_r($result);
?>

Output:

Array
(
[name] => JOHN
[age] => 30
[city] => NEW YORK
)

4. Combining with Other `Arr` Methods

You can chain `Arr::map()` with other `Arr` methods for more complex transformations:

<?php
use Illuminate\Support\Arr;

$array = [
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
];

$result = Arr::map($array, function ($item) {
return Arr::only($item, ['name']);
});

print_r($result);
?>

Output:

<?php
Array
(
[0] => Array
(
[name] => John
)
[1] => Array
(
[name] => Jane
)
)
?>

Points

1. Non-Destructive:
– `Arr::map()` does not modify the original array; it returns a new array.
2. Supports Keys:
– The callback function receives both the value and key of each array element.
3. Flexible:
– You can use any callable function, including closures, static methods, or invokable classes.

When to Use `Arr::map()`

-> When you need to transform array values without writing a loop.
-> When working with associative arrays and need to process both keys and values.
-> When combining array transformations with other `Arr` utility methods.