Laravel 5: Getting the Last Element of an Array With last

April 11, 2018 —John Koster

The last function is the logical opposite of the head function: it will return the last element of an array without modifying the array. The last helper function is a wrapper around PHP's end function.

#Signature

The signature of the last function is:

1function last(
2 $array
3);

#Example Use

Using the following array:

1$anotherArray = [
2 'fourth',
3 'fifth',
4 'sixth'
5];

We can get the last element (without removing it) like so:

1$lastElement = last($anotherArray);

At this point, the $lastElement would have the value of sixth. The following function calls are equivalent:

1// Using Laravel's last function.
2$lastValue = last($anotherArray);
3 
4// Using PHP's end function.
5$endValue = end($anotherArray);

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.