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
}
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With