Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement in PHP injected HTML

<? 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.

like image 880
Znarkus Avatar asked May 23 '11 11:05

Znarkus


People also ask

Is there a switch statement in PHP?

The PHP switch Statement Use the switch statement to select one of many blocks of code to be executed.

How does a switch statement work PHP?

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.

What is the alternative to PHP switch?

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.

Is switch faster than if else PHP?

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.


2 Answers

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

like image 149
j_freyre Avatar answered Sep 25 '22 22:09

j_freyre


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.

like image 33
Emyr Avatar answered Sep 22 '22 22:09

Emyr