<? switch ($var): ?> <? case 1: ?> It's 1! <? break ?> <? endswitch ?>
I want to do something like that, in other words use the switch statement in PHP templates. This is possible with the if statement. The above code generates Parse error: syntax error, unexpected T_INLINE_HTML, expecting T_ENDSWITCH or T_CASE or T_DEFAULT
in PHP 5.3. The PHP docs suggests that this should be possible.
Can someone confirm that this doesn't work, or rather, tell me what I'm doing wrong?
Thanks.
The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed.
The switch statement executes line by line (i.e. statement by statement) and once PHP finds a case statement that evaluates to true, it's not only executes the code corresponding to that case statement, but also executes all the subsequent case statements till the end of the switch block automatically.
PHP introduced an alternative of switch-case in the release of the 8th version. In the release of the 8th version of PHP, the match() function is introduced which is the new alternative of switch-case. It is a powerful feature that is often the best decision to use instead of a switch-case.
if / else if / else is more flexible (hence better), but switch is slightly faster because it just computes the condition once and then checks for the output, while if has to do this every time.
I read in the php doc that your example should not work.
Any output (including whitespace) between a switch statement and the first case will result in a syntax error. For example, this is invalid
Try this instead:
<div> <?php switch($variable): case 1: ?> <div> Newspage </div> <?php break; ?> <?php case 2: ?> </div> Forum <div> <?php break; ?> <?php endswitch; ?> </div>
http://php.net/control-structures.alternative-syntax
You have
?>\n\n<?
after your switch which becomes
switch($var): echo "\n\t"; case 1:
Think of your script as PHP with HTML in it, rather than embellished HTML. The PHP binary gets the file first.
You might like to use something like HEREDOC to echo out unescaped HTML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With