Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - get last index of a multidimensional array [duplicate]

Tags:

php

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...

like image 862
Andrew Avatar asked Dec 19 '22 12:12

Andrew


1 Answers

$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);
like image 68
Eric Avatar answered Dec 22 '22 00:12

Eric