PHP Reference ยท Array Functions
PHP array_key_first() and array_key_last()
Reference for PHP array_key_first() and array_key_last(): get the first or last key of any array without moving the internal pointer, added in PHP 7.3.
The array_key_first() and array_key_last() functions return the first and last key of an array. They work for lists and associative arrays alike and do not touch the array's internal pointer, unlike reset(), end() and key().
Both return null for an empty array. They were added in PHP 7.3, and they are the clean way to read the ends of an array: $array[array_key_last($array)] is the last value.
$a = ["x" => 1, "y" => 2, "z" => 3]; echo array_key_first($a); // x echo array_key_last($a); // z
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_key_first(array $array): int|string|null array_key_last(array $array): int|string|null
| Name | Description |
|---|---|
$array |
The array to inspect. |
Return value: the first or last key, or null if the array is empty.
Errors / Exceptions: a TypeError if the argument is not an array.
Usage notes
- They use the array's actual order, not key order. The first key is the first element that was inserted (or sorted into first place).
- Do not compute the last key as
count($a) - 1. That fails for arrays with gaps or string keys. - No pointer side effects.
end($a)andreset($a)move the internal pointer; these functions do not, and they work on a copy-free read. - Empty arrays give
null, so check before using the key:$k = array_key_first($a); if ($k !== null) { ... }. - Polyfills were common before PHP 7.3; you can drop them if you require 7.3 or later.
- For the values, write
$a[array_key_first($a)]or usereset()andend()if you do not mind the pointer.