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.

Continue in the loop

continue keyword is use for continue the current loop. Php also accepts an optional argument to continue several levels of loop.

Ok. Check following code.

for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}

What you expect as the result?
0
1
3
4
But result is...
2
Because
continue print "$i\n"; 
is a single expression. For your expected result you should add a ; after the continue.

I have found this joke from php manual