Wednesday, July 24, 2013

Switch with semicolon

Switch statement use for check same variable with different values. We use break and default keywords with switch.

This is example of switch.
$i = 2;

switch ($i) {
    case 0:
    case 1:
    case 2:
        echo "i is less than 3 but not negative";
        break;
    case 3:
        echo "i is 3";
        break;
    default:
        echo 'this is default';
}

This is result.
i is less than 3 but not negative

Ok. This is a my change. I replace all colon with semicolon looks like following.

$i = 2;

switch ($i) {
    case 0;
    case 1;
    case 2;
        echo "i is less than 3 but not negative";
        break;
    case 3;
        echo "i is 3";
        break;
    default;
        echo 'this is default';
}
Can you guess the result. Check your answer with following.
  1. Result is same. It will give  i is less than 3 but not negative as the result. 
  2. Result is i is 3.
  3. Result is this is default
  4. Result will be notice.
  5. Result will be warning. 
  6. Result will be fatal error. 
No. first one is correct. Because you can use semicolon as same as colon in PHP.

I have found it from php manual.

No comments:

Post a Comment