Search code examples
phpswitch-statementphp-7.4

PHP switch statement problem causes a syntax error


My code:

<?php
    $i = 1;
    switch ($i) {
?>
        
        <?php
            case 1:
        ?>
        $i is 1
        <?php
            break;
        ?>
<?php
    }
?>

This code gives me an error:

Parse error: syntax error, unexpected ' ', expecting case (T_CASE) or default (T_DEFAULT) or '}' in D:\xampp\htdocs\php-mvc\public\test.php on line 5

I know that I can avoid closing php tags and say echo 'text'; but still, how to fix this?


Solution

  • You are breaking the switch syntax off by outputting empty spaces when closing and opening the PHP tag.

    This will work:

    <?php
        $i = 1;
        switch ($i) {
                case 1:
            ?>
            $i is 1
            <?php
                break;
            ?>
    <?php
        }
    ?>