PHP: Advanced Switch Statement
We all know what is a switch statement. Usually we use switch to compare a variable to a set of possible value and determine what action to take if the variable has that value.
For example, supposed we have this code:
if ($i == 0) {
echo 'Zero';
} else if ($i == 1) {
echo 'One';
} else {
echo 'Does...not...compute...';
}
We can transform the above code using switch statement and still keep the same purpose:
switch ($i) {
case 0:
echo 'Zero';
break;
case 1:
echo 'One';
break;
default:
echo 'Does...not...compute...';
}
For a long time I thought that this is the limit of switch statement, comparing a variable to a set of finite values. I thought that switch cannot replace if-then-else when it involves some kind of range.
For example, supposed we have this code: Read the rest of this entry »