Search

Laravel Array Helper Function: array_last

November 19, 2016 —John Koster

last($array, callable $callback = null, $default = null)

The last helper method is the logical opposite of the first (discussed in the article Laravel Array Helper Function: array_first method. The difference is that the last function will return the last value to satisfy the $callback function. If no value is returned from the $callback function, the $default value is returned.

Using the same $isPostFormat function from the array_first article:

1<?php
2 
3use Illuminate\Support\Str;
4 
5$isPostFormat = function($key, $value) {
6 return Str::is('/post/*', $value);
7};

we could get the last post in the following array like so:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$postsArray = [
6 '/post/first-post',
7 '/post/second-post',
8 '/post/last-post'
9];
10 
11$lastPost = Arr::last($postsArray, $isPostFormat);

the value of $lastPost would be:

/post/last-post

#Optional $callback Parameter

The $callback function is an optional parameter, and can be omitted. When the $callback parameter is omitted, the last method will return the last item in the array:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5// 'something else'
6$firstItem = Arr::last($sampleArray);

#array_last($array, $callback, $default = null)

The array_last function is a shortcut to calling Arr::last. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.