- PHP

Switch and Case without Default in PHP

PHP’s switch doesn’t always need a default case.

It’s not required, but usually you should use it to handle the unexpected value.

Here is an example of switch() without default:

<?php

$rank = 'user';

switch ($rank) {
    case 'admin':
        echo '[Admin Control Panel]';
        break;
    
    case 'moderator':
        echo '[Moderator Control Panel]';
        break;
}

?>

As you can see, in this case, our switch do something only for specific ranks. Because of that, there is no need for having an empty default.