0

I have an array:

$someArray = array('fb' => 32, 'gp' => 11, 'tw' => 7, 'vk' => 89, 'ok' => 112);

As you can see last element in array has the greatest value. I need to return the key(ok) of last element. How to do this?

1
  • loop through the array, compare till the greatest value.. Commented Dec 1, 2013 at 23:08

1 Answer 1

5

Based on https://stackoverflow.com/a/1461363/1641835:

$someArray = array('fb' => 32, 'gp' => 11, 'tw' => 7, 'vk' => 89, 'ok' => 112);
$max_keys = array_keys($someArray, max($someArray));
// $max_keys would now be an array: [ 'ok' ]

$max_keys will now be an array of all the keys that point to the maximum value. If you know there will only be one, or you don't care which you retrieve, you could instead use:

$someArray = array('fb' => 32, 'gp' => 11, 'tw' => 7, 'vk' => 89, 'ok' => 112);
$max_key = array_search(max($someArray), $someArray);
// $max_key would now be 'ok'
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.