I have been being asked by some friends of mine, that is in PHP language how to convert If statement into Switch statement (in some cases, using Switch is for shortening code).
At first, I thought that Switch was just only for 'equal' comparison. But actually it is more than just equal. So I did a search, and I found there is a way that can code Switch just like If. Well, I'm lazy to explain, so let's see the following sample codes of getting Grade from Score:
If statement:
$score=78;
if ($score>=85): echo "Grade A";
elseif ($score>=70): echo "Grade B";
elseif ($score>=55): echo "Grade C";
elseif ($score>=40): echo "Grade D";
else: echo "Grade E";
endif;
Switch statement:
$score=78;
switch(true) {
case $score>=85: echo "Grade A"; break;
case $score>=70: echo "Grade B"; break;
case $score>=55: echo "Grade C"; break;
case $score>=40: echo "Grade D"; break;
default: echo "Grade E";
}
Both code produces same result, that is "Grade B".