More switch() Abuse – Switching on Multiple Values

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 (===).

Tags: , , ,

  1. Jasper’s avatar

    You can:

    switch(true) {
    case $a === true && $b === true :
    break;
    }

    If you need identicality (awesome new word). Certain you already know this, but just in case.