31

Switch on True (2008)

 4 years ago
source link: https://www.tuicool.com/articles/neI77zU
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 seekingthe truth, eh?

Last Updated: 2008-11-05 17:37:02


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK