4

As I read though how to get the last value of multidimensional array, end(array) has come up multiples times. My problem is similar, I have an array like this:

array = (
[12] => Array (xxx => xxx),
[34] => Array (xxx => xxx),
[56] => Array (yyy => yyy)
);

I want to get the index number. If I use end(array) I will get the whole array indexed from [56]. How do I get [56] itself instead of the array?

P.S. I know I can use loop to get the last index number, I just don't want to loop though the whole array to just get the last index number...

Andrew
  • 2,810
  • 4
  • 18
  • 32

1 Answers1

11
$keys = array_keys($yourArray);
$lastKey = $keys[count($keys)-1];

So, get the keys and pick the last one, does this suit you?

I wouldn't recommend this on very large arrays though, if you are doing an iterative operation. I believe the array_keys actually loops the array internally (confirm me on this please).

Alternatively, as @Ghost mentioned in a comment, you can point the array to end with end() and use key() on it to get the key (this is more performant):

end($yourArray);
$lastKey = key($yourArray);
Community
  • 1
  • 1
Eric
  • 18,532
  • 2
  • 34
  • 39
  • 2
    yeah just move the pointer to the end then use `key` – Kevin Aug 05 '14 at 07:54
  • This is perfect! Thanks both of you :), so the process is simply moving the internal pointer to the end of an array and use key to get the index. – Andrew Aug 05 '14 at 08:02