Which is better in terms of CPU optimization for a web server? Writing plain HTML and inserting PHP code here and there?
<script type="text/javascript">$(document).ready(function(){$('#search').focus();});</script>
<div id="default">
<div class="left">
<?include(DIR_DIV.'facebook.php')?>
</div>
<div class="right">
<?include(DIR_ADS.'google.300x250.php')?>
</div>
<div class="sep"></div>
</div>
Or writing the all the HTML with echo in PHP?
echo '<script type="text/javascript">$(document).ready(function(){$(\'#search\').focus();});</script>';
echo '<div id="default">';
echo '<div class="left">';
include(DIR_ADS.'google.300x250.php');
echo '</div>';
echo '<div class="right">';
include(DIR_DIV.'facebook.php');
echo '</div>';
echo '<div class="sep"></div>';
echo '</div>'
Does the difference even matter or is it insignificant?
They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .
Echo sends output to the output buffer, If it's embedded in HTML (which is also being sent to the output buffer) then it appears that it writes that to the "source".
Originally Answered: Which is faster in PHP coding? The latter is much preferred and faster. The speed difference is probably irrelevant, but you need to separate HTML from code for maintainability.
The echo() function outputs one or more strings. Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error.
finally, does the difference even matter or is it insignificant?
It doesn't matter performance wise, it's completely insignificant.
It does matter readability wise though - I find the first block far more legible than the second one. Wrapping HTML into PHP code like that doesn't make sense - it becomes harder to debug, for one thing.
First block is what might be called php template, second pure PHP.
It really depends on what you will be writing more. If HTML - use first, if PHP still use first, just separate it to different file and use as template :)
If you were writing an entire page (and a complex one) with echo you may add a little bit of overhead, since all those lines would need to be executed server side.
I try to stay away from that for the readability issue mentioned in the other answer, though there may be cases (like having to branch based on some values) where you may need to use this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With