Why do I need to escape the dollar sign in default but not in case statements?


#1

Take a look at this code:

 switch ($i) {
        case 0:
            echo '$i is 0.';
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            echo '$i is somewhere between 1 and 5.';
            break;
        case 6:
        case 7:
            echo '$i is either 6 or 7.';
            break;
        default:
            echo "I don't know how much \$i is.";
    }

In all case statements we can echo the variable name with the dollar sign, and it will output the variable name. In the default statement, however, we need to escape the $ character, otherwise it outputs the variable's value.

Why is that so?


#2

Because of in switch statements you create multiple if- statements. That simply means, that you have to write less stuff. In this 'case', you switch ($i), and check if it's 0. So if we translate this to an if- statement, it looks like this:

if ($i == 0);
      echo '$i is 0.';

But now we have to check, if $i equals something else. Instead of writing another if- statement, we just build a switch.

switch ($i) {
           case 0;
                echo "$i is 0."
           #This does exactly the same thing!
           case 1;
                 echo "$i is 1."
            #Now we check if $i equals 1.

So switch is a quicker way to write if- statements.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.