Search for highest key/index in an array

Search for highest key/index in an array

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

Stefan Bogdanescu

Founder & Senior Architect

Finding the Highest Key in an Array

When working with arrays, developers often focus on values: finding the maximum value, the first occurrence of a specific item, or aggregating data. However, there is a distinct scenario where you need to inspect the keys themselves. Whether you are managing sparse arrays, tracking indices for pagination, or debugging off-by-one errors in nested structures, retrieving the highest key is a common requirement.

In PHP, the language provides built-in functions like max() and min() that operate on values by default. These functions iterate over the array and compare the content at each index. They do not natively inspect the keys themselves. To find the highest value, you call max($arr). To find the lowest, you call min($arr). But to get the highest key (index), you must explicitly extract those keys first.

The most straightforward approach is to use the array_keys() function. This function returns an array containing all the keys of the input array. Once you have the list of keys, you can pass them to max().

$arr = [1 => 'A', 10 => 'B', 5 => 'C'];

// Extract keys and find the highest one
$highestKey = max(array_keys($arr));

echo $highestKey; // Outputs: 10

This solution is robust because array_keys() preserves the original type of the keys. If your array uses string keys (common in associative arrays), array_keys() returns strings, and max() handles the comparison accordingly. If your array uses integer keys (numeric indices), array_keys() returns integers. It is crucial to remember that max() performs a lexicographical comparison on strings and a numerical comparison on integers.

Consider an array with string keys:

$assoc = ['zebra' => 'Z', 'apple' => 'A', 'banana' => 'B'];
$highestStringKey = max(array_keys($assoc));

echo $highestStringKey; // Outputs: zebra

In this case, max() compares the strings alphabetically. Since 'z' comes after 'b' and 'a' in ASCII order, 'zebra' is returned. This behavior can be a pitfall if you expect numerical sorting on string keys that look like numbers. For example, '100' would be considered greater than '20' in a strict string comparison, whereas numerically 20 is less than 100. If your keys are numeric strings and you need numerical comparison regardless of their type, you might need to cast the result or ensure consistency before calling max().

Another method involves using array_key_last() (available since PHP 5.4). This function returns the last key of an array. While this often coincides with the highest key in a numerically indexed sequence, it is not always equivalent to "highest" in terms of value.

$arr = [10 => 'B', 1 => 'A'];
// The highest key is 10.
// But if we iterate or sort differently, the "last" key might differ depending on internal structure.
// Actually, in a standard array, keys are not necessarily sequential.

Wait, array_key_last() returns the last element's key as stored in the internal table of the hash table. In PHP, arrays are implemented as hash tables. The "last" key is not necessarily the numerically highest key if the array is sparse or unsorted. However, for standard sequential numeric arrays where keys increment by 1, array_key_last() and the highest key often align. If you have a sparse array like [0 => 'A', 100 => 'B'], the internal structure might not guarantee that array_key_last() returns 100 in all contexts without careful consideration of how the hash table iterates, though typically array_key_last does return the last inserted key's numeric value if it is higher. Actually, array_key_last returns the last element's key. In a sparse array [10 => 'A', 20 => 'B'], array_key_last returns 20. But in a sparse array where insertion order matters differently than numerical order? No, PHP arrays maintain insertion order for iteration, but array_key_last specifically returns the last key.

Actually, let's correct that mental model. array_key_last() returns the last element's key. In an associative array or a sparse numeric array, the "last" key in terms of iteration order is not necessarily the highest numerical value. For example:

$arr = [10 => 'A', 1 => 'B'];
// If we insert 10 then 1? No, keys define positions.
// Let's say: $arr[10] = 'A'; $arr[1] = 'B';
// The internal hash table might store them such that iteration order is not strictly numerical.
// However, array_key_last() returns the last key in the internal list.

Actually, array_key_last() is often used to get the index of the last element added. If you populate an array sequentially:

$arr = [];
$arr[] = 'A'; // 0
$arr[] = 'B'; // 1
// array_key_last returns 1.

But if you do:

$arr[10] = 'A';
$arr[1] = 'B';
// Which one is last? It depends on insertion order. If 10 was added first, then 1, the last key is 1.
// But numerically 10 > 1.

So array_key_last() is not a reliable way to find the highest numerical key in a sparse or randomly indexed array. It finds the highest key based on insertion order (the last one put into the array), not the highest numerical value. Therefore, for finding the absolute highest numerical key regardless of insertion order, max(array_keys($arr)) is the correct and safe approach.

If performance is a critical factor and you are dealing with very large arrays where calling array_keys() (which copies all keys into a new array) causes memory overhead, you might consider iterating manually or using array_search with a specific comparator if available (though PHP doesn't have a built-in key-max function). However, for most use cases, the clarity and correctness of max(array_keys($arr)) outweigh the minor performance cost of copying the keys.

In Laravel applications, this logic remains consistent whether you are working with plain PHP arrays or collections. While Laravel's collect() helper provides many utility methods, it does not expose a direct maxKey() method. You would typically convert a collection to an array or use pluck if needed, but the underlying mechanism is still rooted in PHP's native functions.

$users = collect(['id' => 10, 'name' => 'Alice']);
// To find the highest key here (if keys are dynamic):
$maxKey = max($users->toArray()->array_keys()); // Note: array_keys() on a collection is not direct
// Better to cast to array first:
$usersArray = $users->all();
$maxKey = max(array_keys($usersArray));

Ultimately, the max(array_keys($arr)) pattern is the standard solution. It is explicit, readable, and handles both numeric and string keys correctly according to PHP's comparison rules. Always verify if your array contains mixed key types or sparse indices before relying on this method, as the result will depend on whether you want lexicographical or numerical sorting of those keys.

Our network