rank error in php displaying one rank only

$avr = intval($result->markk / 11); 
$numbers = array($avr);
rsort($numbers);

$arr = $arr1 = array();
$i = $rank = 1;

foreach ($numbers as $key => $value) {

    $arr[$value][] = $value;
}

foreach ($arr as $key => $value) {
    foreach ($value as $key1 => $value1) {
        echo $value1 . "- rank " . $rank . "<br>";
        $rank++; // Increment the rank
    }
    $i++;
}

the above code is showing one rank only how i can fix that

rank 1
rank 2
rank 2
rank 4

>Solution :

You need to put all the students’ averages in $numbers, not just one average.

To get the same rank for tied scores, you should increment $rank in the outer loop, not the inner loop. Increment it by the number of tied scores.

There’s no need for $arr1 or $i. And your loops never use the keys, so you don’t need $key => in `foreach.

$numbers = [];
foreach ($results as $result) {
    $numbers[] = round($result->markk / 11);
}

$arr = [];
foreach ($numbers as $value) {
    $arr[$value][] = $value;
}

$rank = 1;
foreach ($arr as $value) {
    foreach ($value as $value1) {
        echo $value1 . "- rank " . $rank . "<br>";
    }
    $rank += count($value);
}

Leave a Reply