views:

63

answers:

5

I have a switch statement that has over 300 case statements.

  case 'hello': 
    { $say = 'some text'; }
        break;

case 'hi':
    { $say = 'some text'; }
        break;

Why is it that the break is always on a separate line? Is this required? Is there anything syntactically incorrect about me doing this:

  case 'hello': { $say = 'some text'; } break;
  case 'hi': { $say = 'some text'; } break;
+1  A: 

No, PHP is whitespace-insensitive. Semicolons and braces separate statements.

The break is usually on a separate line because it's good style not to place multiple statements on the same line, and to make the control flow of the switch statement clear.

rjh
+1  A: 

Both your examples are possible. By the way, I don't think the brackets are necessary in this case, you could also write:

switch ($myVar) {
    case 'hello': $say = 'some text'; break;
    case 'hi': $say = 'some text'; break;
    default: $say = 'something'; break;
}
Daan
+3  A: 

There is nothing wrong with having the break on the same line. You also don't need the brackets.

However have you considerered rather than having a 300 case switch statment you use another method. A map of keys to values (using an array) would be faster and more maintainable.

$myArray = array(
    'hello' => 'some text',
    'hi'    => 'some text',
);

if ( isset($myArray[$switchKey]) ){
    $say = $myArray[$switchKey];
}else{
    //default case
}
Yacoby
+1. Every time you use one of your 300 case clauses, I'll kill a cat.
Roberto Aloi
@Roberto haha, please don't kill any cats. I will not use those case clauses. Yacoby's answer is great and definitely best practice. Sorry for exposing you to switch case horror.
brett
A: 

Yes, you can put break statement in the case block , It will just seeking for break statement
to close switch case .

pavun_cool
A: 

as an aside, I'd suggest using something like php_codesniffer for advising you re coding styles.

kguest