Vadivel Murugan M - 1 year ago 115

PHP Question

I want to calculate the rank of the students. Condition for rank calculation is, If two or more students have same total marks they all will get same rank. Then the next rank will start from Previous_rank + Number of Duplicate records.

Here is my code:

`<?php`

$numbers = array( 101, 201, 301, 301, 401, 501, 501);

rsort($numbers);

$arrlength = count($numbers);

$rank = 1;

$rt=0;

for($x = 0; $x < $arrlength; $x++) {

if ($x==0) {

echo $numbers[$x]."- Rank".($rank);

}

elseif ($numbers[$x] != $numbers[($x-1)]) {

echo $numbers[$x]."- Rank".($rank);

$rt=$rank;

}

else{

echo $numbers[$x]."- Rank".($rt);

}

$rank++;

echo "<br>";

}

?>

My Expected output is like

`501- Rank1`

501- Rank1

401- Rank3

301- Rank4

301- Rank4

201- Rank6

101- Rank7

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

This code does what you want

```
<?php
$numbers = array( 101, 201, 301, 301, 401, 401, 401, 501, 501, 501, 501);
rsort($numbers);
$arrlength = count($numbers);
$rank = 1;
$prev_rank = $rank;
for($x = 0; $x < $arrlength; $x++) {
if ($x==0) {
echo $numbers[$x]."- Rank".($rank);
}
elseif ($numbers[$x] != $numbers[$x-1]) {
$rank++;
$prev_rank = $rank;
echo $numbers[$x]."- Rank".($rank);
}
else{
$rank++;
echo $numbers[$x]."- Rank".($prev_rank);
}
echo "<br>";
}
?>
```

The problem was with the $rt variable, which you set to 0 but instead should have tracked the previous rank.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**