0

I have 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() because that will return the value 'hello2'.

What function should I use?

ajsie
  • 77,632
  • 106
  • 276
  • 381

3 Answers3

8

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
  • 95,432
  • 20
  • 163
  • 226
2

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
  • 507,862
  • 82
  • 626
  • 550
0
count($array) - 1

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

Anon.
  • 58,739
  • 8
  • 81
  • 86