4,000 emails/month for free | Mailtrap sends real emails now!

Native array_first() and array_last() Functions in PHP 8.5

Last updated on by

Native array_first() and array_last() Functions in PHP 8.5 image

PHP 8.5 will include array_first() and array_last() functions. While on the surface, these functions might not seem like a huge deal (and the PHP community has userland implementations and polyfills), these functions are a long overdue as native functions in the PHP language.

These functions complement the already provided array key methods merged in PHP 7.3:

In PHP 7.3, we got array_key_first() and array_key_last() to get the first and last keys from an array. What we don't have yet is a way to get the first and last values of an array. This is harder than you may think because:

  • The array keys are not necessarily integers, not necessarily starting with 0, etc...
  • Existing “tricks” like reset() and end() are semantically the wrong approach because they modify the “internal iterator” of the array. Furthermore, it also does not work properly on all types of expressions (e.g. an array returned from a function / plain array can cause a notice due to the by-ref argument).
  • Using $array[array_key_first($array)] is cumbersome

As you'll see, a seemingly easy problem to solve (getting the first or last element from an array) has many different solutions that will confuse newcomers to PHP.

So, how do these functions work?

As explained in the array_first_last RFC, here are the function signatures and examples of various types of arrays and scenarios (i.e., no references):

// Function signatures
function array_first(array $array): mixed {}
function array_last(array $array): mixed {}
 
// Examples
array_first(["single element"]); // "single element"
array_last(["single element"]); // "single element"
 
array_first([]); // NULL
array_last([]); // NULL
 
array_first([1 => 'a', 0 => 'b', 3 => 'c', 2 => 'd']); // 'a'
array_last([1 => 'a', 0 => 'b', 3 => 'c', 2 => 'd']); // 'd'
 
$str = "hello";
array_first([&$str, false]); // "hello" (no ref)
array_last([false, &$str]); // "hello" (no ref)

Array First/Last Implementations in the Wild

PHP developers have long been able to get the first and last element of an array using frameworks or homemade userland solutions. This Stack Overflow question is an excellent example as to why a native solution for these functions is helpful to newcomers and seasoned developers alike. Here are a few ways to get the first element of an array according to some answers in a Stack Overflow question:

// Using shift or pop
array_shift(array_values($array));
array_pop(array_reverse($array));
 
// Using array_key_first (PHP 7.3+)
$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];
 
// Using reset
// Unfortunately, reset() modifies the array's iterator
reset($arr);

Just read the variety of solutions, and you'll understand just how valuable a native function will be to newcomers learning PHP.

Laravel's First and Last Array Helpers

Laravel has useful helpers for getting the first and last element of an array using the framework's Arr helper:

use Illuminate\Support\Arr;
 
$arr = ['https://laravel-news.com'];
 
Arr::first($arr); // https://laravel-news.com

The Arr::first() method example above works like the upcoming array_first() function. Laravel allows you to pass a custom default value to return if the array is empty, and an optional closure that must pass a truth test if you want to customize the first value returned:

public static function first($array, ?callable $callback = null, $default = null)
{
if (is_null($callback)) {
if (empty($array)) {
return value($default);
}
 
foreach ($array as $item) {
return $item;
}
 
return value($default);
}
 
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return $value;
}
}
 
return value($default);
}

At the heart of this function, the foreach() loop will be the default way this method returns the first element in an array:

foreach ($array as $item) {
return $item;
}
 
return value($default);

To get the last element of an array, Laravel has the Arr::last() method, which also allows a callback and a customizable returned default value:

public static function last($array, ?callable $callback = null, $default = null)
{
if (is_null($callback)) {
return empty($array) ? value($default) : end($array);
}
 
return static::first(array_reverse($array, true), $callback, $default);
}

Without a provided callback, Laravel uses the end() function if the array is not empty. If a callback is provided, this implementation reverses the array and calls the Arr::first() method, effectively getting the last element in an array using the given callback.

Symfony 8.5 Polyfills

The Symfony framework has a polyfill for array_first() and array_last() PHP 8.5 functions:

public static function array_first(array $array)
{
foreach ($array as $value) {
return $value;
}
 
return null;
}

This method is similar to Laravel's solution, but since its a one-to-one polyfill it does not allow customizing the default value - it will be null just like the intended array_first() and array_last() functions.

Symfony's polyfill for array_last() uses current(), which returns the value of the array's element that is pointed to by the internal pointer. If the $array is empty, the value returned is null:

public static function array_last(array $array)
{
return $array ? current(array_slice($array, -1)) : null;
}

Learn More

The code for the RFC proposal has already been implemented and merged into the master branch of the PHP source at the time of writing.

To learn more, check out the RFC proposal for full details: rfc:array_first_last.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article