Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Two new array methods are coming in PHP 8.5 — array_first() and array_last()

Today, if you want to get the first or last element of an array in PHP effectively, you can use the reset() and end() functions respectively.

Here’s how you can do it.

$array = [1, 2, 3, 4, 5];
$first = reset($array); // 1
$last = end($array); // 5

Of course, this is fine, but it has some drawbacks. For instance, both reset() and end() affect the array’s internal pointer, so if you’re doing anything else with the array iteration afterward, you need to keep that in mind.

You can also use the new array_key_first() and array_key_last() functions to get the first and last keys of an array like so.

$array = [1, 2, 3, 4, 5];

$firstKey = $array[array_key_first($array)]; // 0
$lastKey = $array[array_key_last($array)]; // 4

But this is not intuitive and makes the code harder to read.

So, as the title suggests,

PHP 8.5 will introduce two new functions array_first() and array_last() that make it easier to get the first and last elements of an array without affecting the internal pointer and without using the keys.

$array = [1, 2, 3, 4, 5];
$first = array_first($array); // 1
$last = array_last($array); // 5

$array = ['a' => 1, 'b' => 2, 'c' => 3];
$first = array_first($array); // 1
$last = array_last($array); // 3

For empty arrays, both functions return null instead of throwing an error.

$first = array_first([]); // null
$last = array_last([]); // null

And that’s it! Although the RFC for these functions is still under the voting phase, it is expected to be accepted and merged into PHP 8.5 since all the votes are in favor of it.

You can read more about these functions in this RFC.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you enjoy my work (the articles, the projects, my general demeanour... anything really), consider leaving a tip & supporting the site.

Comments?