Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP switch statement (endswitch) gives Parse error for alternative syntax

Tags:

php

I am getting Parse error: syntax error, unexpected '', expecting endswitch (T_ENDSWITCH) or case (T_CASE) or default (T_DEFAULT) in ... with the following code

myview.phtml

<?php switch ($oEx->getCode()): ?>

<?php default: ?>
Stuff

<?php endswitch; ?>

Whereas this is OK

<?php switch ($oEx->getCode()):

endswitch; ?>

Why? A work around is to add a dummy-case as below before the closing tag but I can't see why this should be necessary.

<?php switch ($oEx->getCode()): case -9999: break; ?>

<?php default: ?>
Stuff

<?php endswitch; ?>
like image 771
daker Avatar asked Feb 11 '15 15:02

daker


1 Answers

See the manual:

Warning Any output (including whitespace) between a switch statement and the first case will result in a syntax error. For example, this is invalid:

<?php switch ($foo): ?>
    <?php case 1: ?>
    ...
<?php endswitch ?>

Whereas this is valid, as the trailing newline after the switch statement is considered part of the closing ?> and hence nothing is output between the switch and case:

<?php switch ($foo): ?>
<?php case 1: ?>
    ...
<?php endswitch ?>

The issue isn't the ending PHP tag, it's the whitespace. I think if you modified your original code as below, it should get rid of your syntax error:

<?php switch ($oEx->getCode()): ?>
<?php default: ?>
Stuff
<?php endswitch; ?>

Notice the only change made is removing the newline between your switch statement and the default case.

like image 144
Jeff Lambert Avatar answered Nov 17 '22 05:11

Jeff Lambert