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.
The signature of the last
method is:
1public static function last(2 $array,3 callable $callback = null,4 $default = null5);
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 $isPostFormat14);
the value of $lastPost
would be:
/post/last-post
$callback
ParameterThe $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<?php2 3use Illuminate\Support\Arr;4 5// 'something else'6$firstItem = Arr::last(7 $sampleArray8);
array_last
Helper FunctionThe array_last
function is a shortcut to calling Arr::last
. This function is declared in the global namespace.
∎
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.