Switch on True (2008)
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
as a bool result). He was stunned that after so many years of programming that hadn't come to me.
true
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
statements, this is for you!
else if
Let me show you what
NOT
to do:
switch(true) {
case ($var=='possible value 1') :
echo $var;
break;
case ($var=='possible value 2') :
error_log($var);
break;
default: // 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.
if ($var=='possible value 1') {
echo $var;
} else if ($var=='possible value 2') {
error_log($var);
} else {
// do nothing
}
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
...besides, now we can say that we are truly seekingthe truth, eh?
switch(true)
Last Updated: 2008-11-05 17:37:02
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK