Search code examples
phpconditional-operatorinline-scripting

A different angle on How to write html code inside php?


We write PHP code inside the HTML code via <?php ... ?> tags. So normally it would not make sense to write HTML code inside PHP code that is already inside HTML code, if you can just exit the PHP for the lines you need. But what if you need the HTML code in the same line as you have the PHP code?

My example would go like this:

<div>
    <?php ($bool) ? <script>...</script> : <script></script> ?>
</div>

Is this:

<div>
    <?php if($bool): ?>
        <script>...</script>
    <?php else: ?>
        <script>...</script>
    <?php endif; ?>
</div>

the only way?

Note: instead of <script> you could have <h1>, <strong>, <title> or any other "one-liner".

Thank you in advance.


Solution

  • Sure, alternative syntax would be the way to go when you have multiple lines of HTML, as you already stated...

    However, for one liners, you can shorten <?php echo '...' ?> with <?= '...' ?> and wrap your HTML within single or double quotes, depending if you are already using double quotes within your HTML syntax. You may also escape them if you like, but that'd be messy.

    <div>
        <?= ($bool) ? "<script>...</script>" : "<script></script>" ?>
    </div>