Get Last Array Element in PHP and Laravel

Get Last Array Element in PHP and Laravel

How to get the last item in the array?

ยท

2 min read

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 ๐Ÿ‡ฎ๐Ÿ‡ณ