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

In Laravel 11.x & Laravel 12.x, the Arr::last() method is a utility provided by the Illuminate\Support\Arr class. It is used to retrieve the last element of an array that passes a given truth test (callback). If no callback is provided, it simply returns the last element of the array.

How Arr::last() Works?

-> If no callback is provided, it returns the last element of the array.
-> If a callback is provided, it iterates through the array and returns the last element that satisfies the callback condition.
-> If the array is empty or no element satisfies the callback, it returns the $default value (or null if no default is provided).

Examples

1. Get the Last Element of an Array

use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$lastElement = Arr::last($array);
// Output: 5
echo $lastElement;

2. Get the Last Element That Satisfies a Condition

use Illuminate\Support\Arr;

$array = [10, 20, 30, 40, 50];
$lastElement = Arr::last($array, function ($value, $key) {
return $value > 25;
});

// Output: 50
echo $lastElement;

3. Provide a Default Value

If the array is empty or no element satisfies the condition, you can provide a default value.

use Illuminate\Support\Arr;

$array = [1, 2, 3];
$lastElement = Arr::last($array, function ($value, $key) {
return $value > 10;
}, 'No match found');

// Output: "No match found"
echo $lastElement;

4. Working with Associative Arrays

Arr::last() works seamlessly with associative arrays.

use Illuminate\Support\Arr;

$array = [
'a' => 10,
'b' => 20,
'c' => 30,
];
$lastElement = Arr::last($array);

// Output: 30
echo $lastElement;