Search code examples
phphtmlmixing

Are there any restrictions on when you can mix HTML and PHP?


I was surprised to find that you can break out of a PHP function into raw HTML and back. I knew that you could do this sort of thing with loops and conditionals, but this was a surprise to me. Is it an accident or is this well-defined behavior? (I couldn't find any explicit discussion of the function case in the manual.)

[NOTE: The following code doesn't give a good example of when I would use this behavior, but I kept it simple for demonstration purposes.]

<?php

$i = 0;

while($i++ < 3) {
    ?><p>I am in a while loop.</p><?php
}

// this part surprised me
function actSkeptical($adjective) {
    ?><p>Is it <?= $adjective ?> that this works?.</p><?php
}

actSkeptical("weird");
?>

Output:

I am in a while loop.

I am in a while loop.

I am in a while loop.

Is it weird that this works?

I know some people absolutely hate mixing PHP and HTML like this, but I can't do OOP/templating (for reasons I won't go into here) and I do like seeing as much raw HTML as possible.

Also, I don't quite understand the semantics of how the short open/close tag above (outputting $adjective) works in conjunction with the surrounding code. Does PHP just treat raw HTML like it was an echo statement? And then the <?= $adjective ?> is just like including a variable within a string?


Solution

  • I can't seem to find any documentation relating to the exiting of PHP tags within blocks. However, there's really only a few places escaping to HTML will work.

    1. Normal Usage

      <?php
      
          php_related_code();
      
      ?>
      
      //html/css/js/etc
      
    2. Within blocks, such as while, for, functions, etc

      <?php
      
      for ($i = 0; $i < 5; $i++) {
          ?>
      
          hello world
      
          <?php
      }
      
      $i = 5;
      while ($i-- > 0) {
          ?> hello there <?php
      }
      
      function myFunc() {
      ?>
          hello universe
      <?php
      }
      
      myFunc();
      

    You can think of ?>stuff<?php similar to an echo or print command found in PHP, because you can escape to HTML in the same places you can echo. So you can echo within the main script, in for loops, and you can echo in functions. But you can't echo in an array, for example:

    <?php
    
    $array = array(echo "here"); //not allowed
    $array = array(?>here<?php); //also not allowed
    

    So you can think of escaping the same as echoing in which it can tell you where you can use it, but you can't do the same thing when you're thinking about what it does.

    They act differently and are processed by PHP differently as well. But your question is only asking about any restrictions so I won't go into what are the differences between ?><?php and echo.

    I forgot to mention, <?=$variable?> is just short tag for <?php echo $variable; ?> if you have this feature enabled.