phparraysrankingdense-rank

Calculate dense rank from highest to lowest number


I have an array of players each with a number of points.

I can easily sort the array in order of the points using a custom usort function.

But when two players have the same amount of points I need to rank them as the same winning position within the list.

E.g.

In this case the data that I require would be

So players with equal scores are designated the same ranking position.

What is the best way of calculating these positions?


Solution

  • This will give you what you want with an additional fix: if you have two players in position 2 the next player should be in position 4. If you don't want this additional fix move $count++; into the if statement.

    $count = 0;
    $position = 0;
    $last_score = -1;
    
    foreach ($players as $player)
    {
        $count++;
    
        if ($last_score !== $player->score)
        {
            $position = $count;
        }
    
        $player->position = $position;
        $last_score = $player->score;
    }