5

How can I make following code more elegant? Currently I have to manually add each condition. Is there a way that I can check if the value of $total_points lie between consecutive terms of the array $ranking_list?

function ym_rank(){
$ranking_list = array(0, 400, 1000, 2500, 5000, 10000, 15000, 25000, 40000, 60000, 100000);
    if($total_points >= $ranking_list[0] and $total_points < $ranking_list[1]){
        return '<h2>Rank 0 </h2><br>';
    }
    elseif ($total_points >= $ranking_list[1] and $total_points < $ranking_list[2]){
        return '<h2>Rank 1 </h2><br>';
    }
    .
    .
    .
    so on
}
3
  • Is there a special reason 5000 is repeated in your list?
    – OIS
    Oct 2, 2013 at 17:16
  • No, it's a typo. I'll edit it.
    – Hacktacus
    Oct 2, 2013 at 17:17
  • 2
    one very minor point here is that all the answers as well as your example presume that the array is ordered. If you want to be sure, then sort it prior to running your tests. It may be also be advisable to assign the rank as a value alongside the min-value of for the rank (explicit) rather than using the key (implicit).
    – horatio
    Oct 2, 2013 at 17:27

2 Answers 2

8

I would use

for ($i = count($ranking_list) - 1; $i >= 0; $i--)
    if ($total_points > $ranking_list[$i])
        return 'Rank is' . $i . '<br>'.

Maybe you should shift index a bit, but the point is, when you go backwards, you don't need two comparisons (and operator).

2
  • Sry, almost the same answer. I was editing so I couldn't see yours :( Oct 2, 2013 at 17:22
  • This works perfectly. Also as @horatio pointed out it is better to sort the list in ascending order (one mentioned in question already is). Thanks!
    – Hacktacus
    Oct 2, 2013 at 17:37
3

you can go for something like this (untested)

for($i = 0; $i < count($ranking_list); $i++){
  if($total_points >= $ranking_list[$i] and $total_points < $ranking_list[$i+1]){
    return '<h2>Rank ' . $i . ' </h2><br>';
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.