Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve elseif condition

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
}
like image 387
Hacktacus Avatar asked Oct 02 '13 17:10

Hacktacus


People also ask

How does ElseIf improve conditional statements?

If / Else / Else If conditional statements are conditional statements that have more than one condition. If the first condition is false, only then will the second condition will be checked. If the second one is also false, then the app will default to else or it will do nothing.

Which is better if-else or if ElseIf?

In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.

How do you make an if statement more efficient?

Efficient if-else StatementsWhile in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.


1 Answers

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).

like image 60
Serge Seredenko Avatar answered Oct 07 '22 16:10

Serge Seredenko