Pootie Tang Pootie Tang - 4 months ago 8
PHP Question

Switch/Case not working PHP

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?

Answer

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'];
}
Comments