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

0

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

yeah just move the pointer to the end then use key
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.