Thursday, October 18, 2007

Switch with expressions

The switch usually are very useful, but also very limited. Looking the way, we can extend its use to evaluate expressions, and call functions. What we have to do is put expressions in the case to be an argument to compare.

For example, we can do the following



switch (true) {
case ($variable >= 0 && $variable < 3):
echo '$variable está entre 0 y 3';
break;

case ($variable >= 3 && $variable < 7):
echo '$variable está entre 3 y 7';
break;

case ($variable >= 7):
echo '$variable es mayor a 7';
break;
}



Thus, instead of using three chained IFs, we can resort to this option, so that our code is more readable.

No comments: