Search

Laravel 5: Finding the Last Occurrence of an Element Matching a Condition With last

April 11, 2018 —John Koster

The last helper method is the logical opposite of the 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.

#Signature

The signature of the last method is:

1public static function last(
2 $array,
3 callable $callback = null,
4 $default = null
5);

#Example Use

The following section builds of the code example we covered in the first section; using it, we can find the last post in a list that matches the /post/* format:

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

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(
12 $postsArray,
13 $isPostFormat
14);

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(
7 $sampleArray
8);

#Global array_last Helper Function

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.