tags:

views:

52

answers:

3

i've got an array like this:

array[0] = "hello0" array[1] = "hello1" array[2] = "hello2"

now i want to get the last key '2' of the array. i cant use end() cause that will return the value 'hello2'.

what function should i use?

A: 
count($array) - 1

Won't work if you've added non-numeric keys or non-sequential keys.

Anon.
+2  A: 

If the keys are not continuous (i.e. if you had keys 1, 5, 7, for example):

$highest_key = rsort(array_keys($myarray))[0];

If they are continuous, just use count($myarray)-1.

Amber
Hey, since when is the function(args)[key] syntax allowed?
Alix Axel
Also, I think you mean to use array_reverse() instead of rsort(), no?
Alix Axel
No, I meant rsort(). `array_keys()` may not always return the keys in sorted order.`
Amber
+8  A: 

end() not only returns the value of the last element but also sets the internal pointer to the last element. And key() returns the key of the element this internal pointer currently ...err... points to.

$a = array(1=>'a', 5=>'b', 99=>'d');
end($a);
echo key($a);

prints 99

VolkerK