How to get last key in an array?

How to get last key in an array?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Illusion of Array Keys and How to Retrieve the Last One

Retrieving the last key from an array is a common task, yet the approach you take depends entirely on what kind of array you are dealing with. In PHP, arrays come in two distinct forms: indexed arrays containing integers starting from zero, and associative arrays mapping string keys to values. The method to extract the final key differs significantly between these types, and using the wrong one can lead to unexpected results or runtime errors.

For indexed arrays, where keys are sequential integers, the most efficient and idiomatic solution is array_key_last(). This built-in function returns the last integer index of a non-empty array. It operates in constant time, O(1), making it significantly faster than iterating through the entire list to find the end. If you are working with a standard list of items—like a collection of user IDs or status codes—this is your go-to tool.

$users = [101 => 'Alice', 102 => 'Bob', 103 => 'Charlie'];

// Using array_key_last() on an indexed-like structure
if (!empty($users)) {
    $lastKey = array_key_last($users);
    echo "Last key: " . $lastKey; // Outputs: 103 (or the highest integer index)
} else {
    echo "Array is empty.";
}

However, developers often confuse this with associative arrays. Consider an array where keys are explicitly defined as strings or mixed types:

$metadata = ['name' => 'Laravel', 'version' => 10, 'author' => 'Taylor'];

Here, array_key_last() will return the highest integer key found within the array. In this specific example, it would return 10 (the integer value of the version key) rather than 'version'. This behavior can be a subtle trap. If your logic assumes the returned value is always a string representing the last associative element, you will encounter bugs when integer keys exist in the mix.

To reliably get the last key of an associative array regardless of whether it contains integers or strings, you must iterate through the keys. The standard end() function moves the internal pointer to the last element, and key() retrieves the associated key string. This approach is universally safe for associative data structures but carries a hidden cost: it relies on the internal pointer state. If your codebase modifies the array between setting the pointer with reset() or next() and calling end(), you might retrieve an incorrect key or trigger a warning if the pointer has gone past the end of the array.

$metadata = ['name' => 'Laravel', 'version' => 10, 'author' => 'Taylor'];

// Reset pointer first to ensure safety before using end()
reset($metadata); 

if (!empty($metadata)) {
    end($metadata);
    $lastKey = key($metadata);
    
    // $lastKey will be 'author' because it is the last element in this specific array
    echo "Last associative key: " . $lastKey; 
}

There is another edge case to consider: arrays with sparse indices or non-sequential integers. If you have an indexed array like [0 => 'a', 5 => 'b', 9 => 'c'], array_key_last() correctly returns 9. While this technically gives the last index, it does not necessarily represent the last element in a logical sequence if gaps are significant. In such scenarios, understanding whether you need the highest index or the last defined element becomes crucial for your application logic.

If you find yourself frequently needing to inspect array structures without worrying about pointer overhead or key type confusion, checking the Laravel documentation is always a good practice. Resources like https://laravelcompany.com can offer deeper insights into collection methods that abstract these low-level array operations away, allowing you to work with collections more safely. However, for raw arrays, mastering array_key_last() and end() combined with reset() ensures you have full control over your data access patterns.

Our network