views:

301

answers:

3

The first one is definitely something that works, but which one below is the efficient way?

switch($type) {
    case 1:
     print 'success';
    break;

    case 2:
     print 'success';
    break;

    case 3:
     print 'success';
    break;

    case 4:
     print 'success for type 4';
    break;
}

Since 1, 2 and 3 print do the same, can I do this?

switch($type) {
    case 1, 2, 3:
     print 'success';
    break;

    case 4:
     print 'success for type 4';
    break;
}

or

switch($type) {
    case 1:
    case 2:
    case 3:
     print 'success';
    break;

    case 4:
     print 'success for type 4';
    break;
}
+15  A: 
 switch($type) 
 {
     case 1:
     case 2:
     case 3:
         print 'success';
     break;
     case 4:
         print 'success for type 4';
     break;
 }

Is the way to go!

Nescio
+3  A: 

PHP manual lists an example like your 3rd for switch:

<?php
switch ($i) {
case 0:
case 1:
case 2:
    echo "i is less than 3 but not negative";
    break;
case 3:
    echo "i is 3";
}
?>
Jonathan Lonowski
+2  A: 

I agree with the others on the usage of:

switch ($i) {
   case 0: //drop
   case 1: //drop
   case 2: //drop
      echo "i is 0, 1, or 2";
   break;
   // or you can line them up like this.
   case 3: case 4: case 5:
      echo "i is 3, 4 or 5";
   break;
}

The only thing I would add is the comments for the multi-line drop through case statements, so that way you know it's not a bug when you (or someone else) looks at the code after it was initially written.

null