|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2019-07-17 10:03 UTC] benjamin dot morel at gmail dot com
Description:
------------
When using PHP as a template engine, it can be useful to break statements into separate code blocks. For example, this works fine with foreach:
<?php foreach ($users as $user): ?>
<span><?= ... ?></span>
<?php endforeach; ?>
The same thing does not work with switch:
<?php switch ($type): ?>
<?php case 'a': ?>
<span>...</span>
<?php break; ?>
<?php case 'b': ?>
<span>...</span>
<?php break; ?>
<?php endswitch; ?>
Which fails with a parse error:
> Parse error: syntax error, unexpected ' ', expecting endswitch (T_ENDSWITCH) or case (T_CASE) or default (T_DEFAULT)
For this to work, the first case must be in the same code block as the switch. This works fine:
<?php switch ($type):
case 'a': ?>
<span>...</span>
<?php break; ?>
<?php case 'b': ?>
<span>...</span>
<?php break; ?>
<?php endswitch; ?>
I believe this is a bug.
Test script:
---------------
<?php $type = 'a'; ?>
<?php switch ($type): ?>
<?php case 'a': ?>
This is A
<?php break; ?>
<?php case 'b': ?>
This is B
<?php break; ?>
<?php endswitch; ?>
Expected result:
----------------
This is A
Actual result:
--------------
Parse error: syntax error, unexpected ' ', expecting endswitch (T_ENDSWITCH) or case (T_CASE) or default (T_DEFAULT) in ...
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 03 01:00:01 2025 UTC |
As the error message indicates, your problem here is the indentation. Doing something like <?php switch ($type): ?> <?php case 'a': ?> will work fine. But as you indented the case block, you are basically doing the equivalent of: switch ($type): ; echo ' '; case 'a': which is of course not allowed.Thanks for the explanation! I forgot about the collapsing newline (but not spaces) after the closing tag. Although this makes sense, it's also very confusing in the present case (pun intended). First of all this obviously also happens when both lines are indented: Works: <?php switch ($type): ?> <?php case 'a': ?> ... Fails: <?php switch ($type): ?> <?php case 'a': ?> ... And it does allow whitespace between 'break' and 'case' blocks: <?php break; ?> <?php case 'b': ?> Which is because, as I just discovered, (unreachable) statements are allowed between break and case in PHP. All in all, the switch...case seems to be the only place that exhibits this odd behaviour. Couldn't the parser handle this edge case?