Skip to main content

Command Palette

Search for a command to run...

Get Last Array Element in PHP and Laravel

How to get the last item in the array?

Published
2 min read
Get Last Array Element in PHP and Laravel

Laravel provides the last() function as a global helper and also as a function defined in Illuminate\Support\Arr that can be used to get the last element in an array.

This article, guide through the different ways of retrieving the last array element in PHP also in Laravel. So you can decide which suits you best.

Retrieve the last element in PHP

In PHP, to get the last element from an array, first, you need to count the total array elements

$languages = [
  'JAVA',
  'PHP',
  'C++',
  'C#',
  'Python',
];
$totalElements = count($languages);
echo $languages[$totalElements - 1];
  • Above code will output Python i.e the last element in a provided array.
  • It is a more readable approach, can also be rewritten in a single line as shown, which sometimes looks complex for beginners.
echo $languages[count($languages) - 1];
Python

Retrieve the last element in Laravel

In Laravel, you can get the last array element in two ways.

  1. Using global last() helper.
  2. Using the static method of Arr class named last().

Using global last() helper

The last() helper function returns the last element in the given array:

$carBrands = [
  'Maserati',
  'Tesla',
  'Tata',
  'Aston Martin',
  'Audi',
  'Alfa Romeo',
];
echo last($carBrands);
  • Above code will output Alfa Romeo i.e the last element in a provided array named $carBrands.

Using last() function in Arr class

  • The last() helper function returns the last element in the given array.
  • Before using it, remember to import using the use Illuminate\Support\Arr; statement.

Syntax

$last = Arr::last($array, $callback, $default);
  • The first parameter is a source array, from which the last element is to be found. It's a required parameter.
  • The second parameter is a callback function, that can be either helpful to filter & retrieve the last element based on conditions. It's an optional parameter.
  • The third parameter is a default value & it will be returned if none of the array elements passes the truth test.
$fruits = [
  'Orange 🍊',
  'Apple 🍎',
  'Grapes 🍇',
  'Kiwi 🥝',
  'Mango 🥭',
];

echo Arr::last($fruits);
  • Above code will output Mango 🥭 i.e the last element in a provided array named $fruits.

Read the complete post on our site Get Last Array Element in PHP and Laravel

Read others post on our site MeshWorld

Happy 😄 coding

With ❤️ from 🇮🇳

H
Helen Dam2y ago

Your article is a lighthouse amidst a tempestuous sea of information, guiding lost voyagers towards the shores of Heardle clarity and understanding. With its steadfast illumination, you have provided a beacon of knowledge that pierces through the fog of confusion, and for this guiding light, I am eternally grateful.

More from this blog