PHP 7.3: Introduced array_key_first() and array_key_last() functions

TypeNew Feature

PHP has over 75 array functions, but there was no easy way to retrieve the first and last keys of an array without modifying the array pointer or retrieving all keys of the array (with array_keys()) and then retrieving the first or last values of the array.

In PHP 7.3, there are two new functions: array_key_first and array_key_last that let you grab the first and last keys of the given array.

The RFC also proposed array_value_first() and array_value_last() functions, but this portion of the RFC didn't get voted.


If you cannot immediately upgrade to PHP 7.3, you can get the same functionality with the two polyfills below.

if (!function_exists('array_key_first')) {
    function array_key_first(array $array) {
        foreach ($array as $key => $value) { 
            return $key; 

if (!function_exists('array_key_last')) {
        function array_key_last(array $array) { 
            return key($array); 

Backwards compatibility impact

Unless you have declared your own array_key_first and array_key_last functions, there shouldn't be any issues.

RFC discussion Implementation