Leading space before php opening tag in switch case statement

253 views Asked by At

As you can see there is a leading space before opening tag in case 1: line:

$var = 1;
switch ($var):

?>
 <?php case 1:?> // BUGGY LINE
    <?php
        echo 1;
        break;
    case 2:
        echo 2;
        break;
endswitch;
?>

It produces error:

( ! ) Parse error: syntax error, unexpected ' ', expecting endswitch (T_ENDSWITCH) or case (T_CASE) or default (T_DEFAULT)

If I remove that space, everything is OK.

What is the reason?

1

There are 1 answers

0
Tom Udding On

This is the default behaviour of the alternative syntax for (switch) control structures. As stated by the documentation:

Any output (including whitespace) between a switch statement and the first case will result in a syntax error.

No matter if you put 1 space there or just any character it will throw an error. There shouldn't be anything between the start of the switch statement and the next piece of the switch statement (a case, default or endswitch).