Highest value of an array key?

Doesn’t actually matter now as I’ve fetched it while building the array, but… Isnt there a function for finding the maximum value of a key in a numeric array? In a numeric array are the keys ordered numerically and not the order in which they were set? I tried imploding array_keys() and sending that to max(), but PHP doesn’t like that idea. I know you can cycle through and test each against the current max, but there must be something more elegant…?

you could always you sort the array by the key then grab the last key…

If you are just manually assigning entries to an array with something like.

while (.....) {
  $data[] = $row;


$maxkey = count($data) - 1;

$maxkey would hold your max key value.


This worked for me:

$test = array("1" => "test", "5" => "bla", "3" => "blubb");

echo max(array_keys($test));

It should also work for keys that are non-numeric.

yet another alternative :): use ksort() to sort the array by key then get the first element


Cheers for the input guys, I’m assuming that as 2 of suggested sorting the array that even in numeric arrays they remain in set order. I’m manually assigning keys in the while loop so count() is no good for me.

Chris, I didn’t know you could send an array to max(), so I tried

$keys = implode (', ', array_keys($array));
$max = max($keys);

But you can’t use a string.