This is an old revision of the document!

PHP RFC: array_key_first() and array_key_last()


As arrays are a powerful data structure it's handy in some cases to get the first or the last key of an array without a workaround. To accomplish this task this RFC adds two functions to the core:

  • $key = array_key_first($array);
  • $key = array_key_last($array);


The current functions of the PHP core only allow to retrieve the first/last key of an array by changing the internal state of the array when using the functions reset(), end() and key(). Other implementation approaches are either inperformant (eg. usage of array_keys($array)[0], which additionally may lead to errors if $array is an empty array) or provide a construct which increases the cognitive complexity of the implementation (eg. usage of loops).

To avoid changes of the internal array representation in order to gather a single information from the array and to increase the comprehensibility of the userland code this RFC proposes two new functions for this task:

To gather the key of the first element of an array the method array_key_first($array) will be added.

To gather the key of the last element of an array the method array_key_last($array) will be added.

// usage of an associative array
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 'a');
assert($lastKey === 'c');
// usage of a numeric array
$array = [1 => 'a', 2 => 'b', 3 => 'c'];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 1);
assert($lastKey === 3);
// usage of an empty array
$array = [];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === null);
assert($lastKey === null);

The functions either return the requested key or null if an empty array is provided.

Backward Incompatible Changes


Proposed PHP Version(s)

next PHP 7.x

RFC Impact

As this RFC adds two new functions there is a possible impact on existing userland extensions where developers created helper functions with an identical name. As the functions proposed provide a meaningful name custom functions should implement an identical functionality and thus be replaceable.

There is no impact to SAPIs or the opcache.

Proposed Voting Choices

As this RFC doesn't change the syntax of PHP a 50%+1 majority is required.

Patches and Tests

The GitHub pull request which provides the functionality and the related tests is located at https://github.com/php/php-src/pull/3256


After the project is implemented, this section should contain

  1. the version(s) it was merged into
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature
  4. a link to the language specification section (if any)
rfc/array_key_first_last.1528728536.txt.gz · Last modified: 2018/06/11 14:48 by wol-soft