php - switch with opentags in html

Viewed 28

I have the following code in a view for setting the selected option for a dropdown I have used loops for this kind of thing before, but never a switch, it is breaking at some point for the syntax. is this even possible in php? sorry if it is a dumb mistake.

    <?switch($_GET['rows']):?>

      <select name="rows"  onchange="$('#paginacao').submit()">

        <option value="10" <?case 10: echo 'selected'; break;?>>10</option>

        <option value="15" <?case 15: echo 'selected'; break;?>>15</option>
        <option value="20" <?case 29: echo 'selected'; break;?>>20</option>
        <option value="100" <?case 100: echo 'selected'; break;?>>100</option>
      </select>

    <?endswitch;?>
1 Answers

While it is confusing that it should work differently for a specific control structure, the switch-case alternative syntax has a specific requirement about output between the start of the switch statement and the first case: There should be none.

Which means that, in your example, that every single character (apart from the line break) between <?switch($_GET['rows']):?> and <?case 10: echo 'selected'; break;?> is causing the syntax error.

However, you can simplify your code by simply using ternary conditions:

<select name="rows" onchange="$('#paginacao').submit()">
    <option value="10" <?php echo ($_GET['rows'] === 10 ? "selected" : ""); ?>>10</option>
    <option value="15" <?php echo ($_GET['rows'] === 15 ? "selected" : ""); ?>>15option>
    <option value="20" <?php echo ($_GET['rows'] === 20 ? "selected" : ""); ?>>20</option>
    <option value="100" <?php echo ($_GET['rows'] === 100 ? "selected" : ""); ?>>100</option>
</select> 
Related