News

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

Published Updated
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

Sponsored

laravelcloud logo
Laravel Cloud

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

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article