mootools php faith camera linux

php

Switch on true



Switch on the value true and feed the case a statement to evaluate.

I was in a bind with how to switch on something at work, and another programmer shared this (probably age-old) coding method of switching on true as a bool result). He was stunned that after so many years of programming that hadn't come to me.

I'm a bit surprised, as well, that I haven't seen it; I make good use of switch to keep my if/else jungle to a bare minimum.

Let me tell you, if you are using a string of else if statements, this is for you!

     
switch(true) {
        case (
$var=='possible value 1') :
          echo 
$var;
        break;
        case (
$var=='possible value 2') :
          
error_log($var);
        break;
        default: 
// do nothing
      
}
Let me show you what NOT to do:

     
if ($var=='possible value 1') {
       echo 
$var;
     } else if (
$var=='possible value 2') {
       
error_log($var);
     } else {
       
// do nothing
     
}
Now I know that it is personal preference, but when you need to put large blocks of code in the switch is much more versatile and easy to read/modify.

"Wait! That could have been done by switching on $var much easier!

Yes, it could have, but this one can not:

     
switch(true) {
        case (
$var<20) :
          echo 
$var;
        break;
        case (
$var>=20) :
          
error_log($var);
        break;
        default: 
// do nothing
      
}

I love that switch(true) ...besides, now we can say that we are truly seeking the truth, eh?

Last Updated: 2008-11-05 17:37:02
Creative Commons License Jay Johnston is a Zend Certified Engineer in PHP 5 LPI-ID: LPI000102450, Verfication Code: wmnnt56y2k  ... Jay Johnston is certified as LPIC-1 by the Linux Professional Institute