Martin Perry Martin Perry - 1 year ago 38
HTML Question

PHP - start / end PHP multiple times in HTML file

I have a HTML file where I am using PHP like this:

<html code>
<?php do something ?>
<?php do something ?>
<?php do something ?>
<?php do something ?>

Is this a good way to go, or should I put entire HTML to PHP
? I mean, I am starting / stopping script inside web page multiple times just because of one output one variable or if some block of the HTML code.

I am doing it this way fo better readibility of HTML/PHP code during development.


Your question of "which way is better" can be broken down into two questions:

  1. Which way is more efficient?

  2. Which way is more readable?

The answer to question 1 is that the difference is negligible. PHP code is made to execute very fast on the server. Usually processes that take long on PHP would be complex functions that require iterations over large amounts of data for instance, however the actual reading of a single tag takes a very small amount of time to be processed.

The answer to question 2 depends entirely on the situation. In your situation, you are constantly adding <?php and ?> tags when you could have done it all at once, so my personal opinion would be to place it all in one echo, however there are many cases where it is more readable to place separate php elements, for example in the following form:

<form action="<?php htmlspecialchars($_SERVER['PHP SELF']);?>" method="POST">
  <?php echo $dynamic_input1'?><br>
  <input type="text" name="text1">
  <?php echo $dynamic_input2'?><br>
  <input type="text" name="text2">

Let me know if that helped.