Pergunta

I'm trying to get into the habit of using switch/case instead of if. I have the following tidbit:

                        switch($res['perm']){
                            case '0': $perm = "Invalid";
                            case '1': $perm = "Operator";
                            case '2': $perm = "Team Lead";
                            case '3': $perm = "Admin";
                            default: $perm = "Unknown - ".$res['perm'];
                        }

Where $res['perm'] = (int) 3 .. I tried without the single quotes as well, but it still defaults to "Unknown" .. What am I doing wrong?

Foi útil?

Solução

You need to break out of the switch or it will always hit default:

switch($res['perm']){
    case '0': $perm = "Invalid"; break;
    case '1': $perm = "Operator"; break;
    case '2': $perm = "Team Lead"; break;
    case '3': $perm = "Admin"; break;
    default:  $perm = "Unknown - ".$res['perm'];
}

Outras dicas

AbraCadaver's answer solved my problem, but I thought I'd share the issue and solution in case it's of use to someone else.

Initially, I didn't enclose my case in quotes.

switch ($month) {
case 01:
    echo "January";
    break;

etc down to December. This worked for all except August and September. The code was fine, (evidenced by the following solutions).

Why just those two months I don't know, but removing the leading 0 solved the problem , as did adding the quotes to the case, which is what I've gone for. So:

switch ($month) {
case '01':
    echo "January";
    break;
case '02':
    echo "February";
    break;
case '03':
    echo "March";
    break;
case '04':
    echo "April";
    break;
case '05':
    echo "May";
    break;
case '06':
    echo "June";
    break;
case '07':
    echo "July";
    break;
case '08':
    echo "August";
    break;
case '09':
    echo "September";
    break;
case '10':
    echo "October";
    break;
case '11':
    echo "November";
    break;
case '12':
    echo "December";
    break;
}

Very odd, but hope this helps someone.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top