Perfect Ranking with ties using PHP alone
<p>In my attempt to find the perfect ranking solution with ties, I was stuck at giving the correct ranking. Codes will explain what I am trying to achieve better:</p>

<p>I have the following array:</p>

<pre><code>$standings = array(
    'player_1' =&gt; 30,
    'player_2' =&gt; 26,
    'player_3' =&gt; 28,
    'player_9' =&gt; 28
);
</code></pre>

<p>Now in order to rank it with ties, I have the following function:</p>

<pre><code>function setRanking($standings) {
    $rankings = array();
    arsort($standings);
    $rank = 1;
    $tie_rank = 0;
    $prev_score = -1;
    foreach ($standings as $name =&gt; $score) {
        if ($score != $prev_score) {  //this score is not a tie
            $count = 0;
            $prev_score = $score; 
            $rankings[$name] = array('score' =&gt; $score, 'rank' =&gt; $rank);
        } else { //this score is a tie
            $prev_score = $score;
            if ($count++ == 0) {
                $tie_rank = $rank - 1;
            }
            $rankings[$name] = array('score' =&gt; $score, 'rank' =&gt; $tie_rank);
        }
        $rank++;
    }
    return $rankings;
}
echo '&lt;pre&gt;';
print_r(setRanking($standings));
</code></pre>

<p>Output:</p>

<pre><code>Array
(
    [player_1] =&gt; Array
        (
            [score] =&gt; 30
            [rank] =&gt; 1
        )

    [player_3] =&gt; Array
        (
            [score] =&gt; 28
            [rank] =&gt; 2
        )

    [player_9] =&gt; Array
        (
            [score] =&gt; 28
            [rank] =&gt; 2
        )

    [player_2] =&gt; Array
        (
            [score] =&gt; 26
            [rank] =&gt; 4
        )

)
</code></pre>

<p>Expected Output:</p>

<pre><code>Array
(
    [player_1] =&gt; Array
        (
            [score] =&gt; 30
            [rank] =&gt; 1
        )

    [player_3] =&gt; Array
        (
            [score] =&gt; 28
            [rank] =&gt; 2
        )

    [player_9] =&gt; Array
        (
            [score] =&gt; 28
            [rank] =&gt; 2
        )

    [player_2] =&gt; Array
        (
            [score] =&gt; 26
            [rank] =&gt; 3
        )

)
</code></pre>

<p>The problem is it prints the ranking as <code>1,2,2,4</code> whereas it should print <code>1,2,2,3</code> according to my assumption. So how can it print 1,2,2,3? Where could thing possibly go wrong? Any help is appreciated. Thanks.</p>