Mastering array_key_first() and array_key_last() in PHP

Mastering array_key_first() and array_key_last() in PHP
Photo by Nathan da Silva / Unsplash

When working with arrays in PHP, it's often necessary to access the first or last element. Starting from PHP 7.3, two dedicated functions — array_key_first() and array_key_last() — make this task more explicit and reliable.


🔍 What Do These Functions Do?

  • array_key_first(array $array)
    Returns the first key of the array.
  • array_key_last(array $array)
    Returns the last key of the array.

Unlike reset() or end(), which operate on the internal pointer and return values, these functions return the actual keys. This makes them especially useful when you need to work with both keys and values.


🧪 Basic Example

$array = [1, 2, 3, 4, 5];

$firstKey = array_key_first($array); // 0
$lastKey = array_key_last($array);   // 4

$firstValue = $array[$firstKey]; // 1
$lastValue = $array[$lastKey];   // 5

This method works for both indexed and associative arrays.


📘 Example with Associative Array

$user = [
    'name' => 'Sony',
    'email' => '[email protected]',
    'location' => 'Jakarta'
];

$firstKey = array_key_first($user); // 'name'
$lastKey = array_key_last($user);   // 'location'

echo $user[$firstKey]; // Sony
echo $user[$lastKey];  // Jakarta

This is much clearer than using pointer functions like reset() or end(), which can obscure the key being referenced.


⚠️ Empty Array Behavior

If the array is empty, both functions will return null.

$data = [];

var_dump(array_key_first($data)); // null
var_dump(array_key_last($data));  // null

You should always check the array's size before accessing elements based on these keys.


🔄 Comparison with reset() and end()

While reset() and end() return the value directly, they also modify the internal pointer of the array, which might affect subsequent operations:

reset($array); // sets pointer to the first element
end($array);   // sets pointer to the last element

In contrast, array_key_first() and array_key_last() are non-intrusive — they do not affect the internal pointer.


Why Use Them

  • Safer for read-only operations.
  • Do not interfere with array iteration.
  • Ideal for associative arrays when key awareness is needed.
  • Work consistently across all array types.

🧵 Finally

The functions array_key_first() and array_key_last() offer a clean and precise way to access array boundaries in PHP. They are a welcome addition to the language, improving code clarity and behavior predictability — especially when dealing with associative arrays or avoiding pointer side effects.

If you’re using PHP 7.3 or newer, it’s time to make these functions a regular part of your toolkit.

Support Us