Skip to content
Advertisement

Find max and min key in associative array

I have associative array like

JavaScript

I want to get lowest and highest key i.e. 1945 and 2012. How can i achieve this? I have already searched over stackoverflow and Hightest value of an associative array is the nearest possibility but it gives out min and max value and I want min and max key.

**I don’t want to use foreach loop **

Advertisement

Answer

If you really hate foreach, here’s a solution:

JavaScript

Your $arr would end up like this:

JavaScript

Now you can use min() and max() functions or sort() it get the highest and lowest value easily.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement