phpsyntaxswitch-statement

default as first option in switch statement?


I've tested this and it works fine, but it looks... weird... to me. Should I be concerned that this is nonstandard form which will be dropped in a future version of PHP, or that it may stop working? I've always had a default case as the final case, never as the first case...

switch($kind)
{
    default:
        // The kind wasn't valid, set it to the default
        $kind = 'kind1';
        // and fall through:

    case 'kind1':
        // Do some stuff for kind 1 here
        break;

    case 'kind2':
        // do some stuff for kind2 here
        break;

    // [...]

    case 'kindn':
        // do some stuff for kindn here
        break;

}

// some more stuff that uses $kind here...

(In case it's not obvious what I'm trying to do is ensure $kind is valid, hence the default: case. But the switch also performs some operations, and then $kind is used after the switch as well. That's why default: falls through to the first case, and also sets $kind)

Suggestions? Is this normal/valid syntax?


Solution

  • It is an unusual idiom, it causes a little pause when you're reading it, a moment of "huh?". It works, but most people would probably expect to find the default case at the end:

    switch($kind)
    {
        case 'kind2':
            // do some stuff for kind2 here
            break;
    
        // [...]
    
        case 'kindn':
            // do some stuff for kindn here
            break;
    
        case 'kind1':
        default: 
            // Assume kind1
            $kind = 'kind1';
    
            break;
    
    }