Search code examples
phparraysranking

Returning the position (Rank) in an array


I have an array:

$age_array = array("Tom" => "20", "Sandra" => "17", "Kevin" => "35");

I sort first the array from old to young and then I want to return the position of Sandra (The rank). Something like:

Sandra - 17 years old - Rank 3

or

Kevin- 35 years old - Rank 1

Any help will be appreciated.

Edit:

I got it to work with this code using array_keys() combined with array_search:

$age_array = array("Tom" => "20", "Sandra" => "17", "Kevin" => "35");
arsort($age_array);
echo array_search("Kevin",array_keys($age_array))+1;

Solution

  • array_keys($age_array) will return an array of the keys from which you can get the rank. See the documentation and some samples here.