0

In Can HTML be embedded inside PHP "if" statement?, the accepted (and most upvoted) answer mentions only the alternative if style.

The other 2 answers mention it works with normal if, as well, but is it standards-compliant, or is it non-standard but supported behavior?

I mean this code:

<?php if ($cond) { ?>
    If branch<br>
<?php } else { ?>
    Else branch<br>
<?php }?>
Community
  • 1
  • 1
sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • 2
    What standards are you referring to? – danronmoon May 25 '14 at 17:07
  • It's not a standard, but most appropriate way of writing this – Yang May 25 '14 at 17:09
  • @danronmoon Well, coming from C++, I was assuming there's a 1000 page PHP standard or something. But basically - are you supposed to do this, or only the alternative if should be used? By the way, that code works, I tested it on PHP5/Apache/chrome. – sashoalm May 25 '14 at 17:11
  • It's like how WordPress devs do that. See `wp-register.php` - that looks hard to read – Yang May 25 '14 at 17:11
  • No, you're not supposed to do this. By doing so, you make PHP code inside html-layots much easier to read and maintain – Yang May 25 '14 at 17:14
  • 1
    Summary: Yes, this is valid PHP syntax. This has always worked and there are no plans that I'm aware of to stop this. – deceze May 25 '14 at 17:17
  • The normal syntax is standard. The alternative syntax is non-standard. Some kids somehow are "lunatic" and favor the alternative syntax, however I never could feel with them. ^^ – hakre May 25 '14 at 17:17
  • Just FYI: From a coding standard perspective, there is not so much in PHP for coding standards. The PSR-2 one says brackets are required for control structures, therefore the alternative syntax is not considered. – hakre May 25 '14 at 17:40

1 Answers1

1

Yes, the standard syntax in PHP works.

As suggested by the term standard I used in my last sentence, I really meant that it is the standard syntax. It always worked. It will always work.

Consider the alternative syntax alternative, that is, non-standard. The wording is from the PHP manual, not from me personally.

Alterantive already suggests that it works exactly the same, so you can use any of those, despite the votes on some Q&A platform somewhere in the world wide web :)


<?php if ($condition) { ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php } ?>

By request, here's elseif and else (which you can also find in the docs: elseif; else)

<?php if ($condition) { ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php } elseif($anotherCondition) { ?>
    more html
<?php } else { ?>
    even more html
<?php } ?>

It's that simple.

The HTML will only be displayed if the condition is satisfied.


I hope this exemplary reqplique does add enough clarity if there were any doubts.

hakre
  • 193,403
  • 52
  • 435
  • 836