Due to working with Drupal for most of this year, I’ve seen this construct so many times it’s killed me a little inside:
switch($a) {
case TRUE:
switch($b) {
case TRUE:
break;
case FALSE:
break;
}
break;
case FALSE:
switch($b) {
case TRUE:
break;
case FALSE:
break;
}
break;
}
Someone I work with, who wishes to keep his name off the net, came up with this:
switch(array($a, $b)) {
case array(false, false):
break;
case array(false, true):
break;
case array(true, false):
break;
case array(true, true):
break;
}
I’d rather avoid the need for nested switches altogether, but this construct makes it easy to collapse similar branches, and is, I think, a useful addition to my toolkit:
switch(array($a,$b)) {
case array(true, true):
break;
case array(false, false):
case array(false, true):
case array(true, false):
default:
break;
}
It’s worth mentioning that arrays are compared for equality (==) rather than identicality (===).
1 comment
Comments feed for this article
Trackback link: http://www.otton.org/2009/11/22/more-php-switch-abuse-switching-on-multiple-values/trackback/