PHP: Breaks in default case switches?

user1307016 picture user1307016 · Aug 21, 2012 · Viewed 10.7k times · Source
switch ($var) {
    case 0:
        // Do something...
        break;
    case 1:
        // Do something...
        break;
    default:
        // Do something...
        break;
}

I've seen some people use break at the end of the default case. Since the default case is the last case that's executed when triggered, is there any need to have a break there? I'm guessing it's just done out of common practice or is there another reason?

Answer

Lusitanian picture Lusitanian · Aug 21, 2012

There's no reason its required so long as the default is at the end of the switch statement. Note that the default doesn't need to be the last case: http://codepad.viper-7.com/BISiiD

<?php
$var = 4;
switch($var)
{
    default:
        echo "default";
        break;
    case 4:
        echo "this will be executed";
        break;
}