Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Look at this:

<?php
echo "Hello World";
?>
<br />
<?php
echo "Welcome";
?>

And now look at this:

<?php
echo "Hello World";
echo "<br />";
echo "Welcome";
?>

Which one of the above examples is considered to better (at least from performance point of view)?.

I know the examples are trivial but I want to follow good practice habits from the beginning so when I have more and more lines they would not affect the performance or whatever in a negative way.

share|improve this question
10  
This doesn't appear to be massively popular in PHP, but note that in other ecosystems, both are considered bad and the proper alternative is to create a template of all static parts with minimal logic to include dynamic parts, and then render it from the programming language. –  delnan Dec 24 '12 at 2:01
    
@delnan - You should consider posting that as an answer, in a slightly expanded form. That is a lot cleaner. –  jmort253 Dec 24 '12 at 2:01
    
@jmort253 Have considered it, but I have very little PHP knowledge, so I couldn't speak for best practices in the PHP world. –  delnan Dec 24 '12 at 2:02
    
What problem are you trying to solve? –  Jim G. Dec 24 '12 at 2:15
    
In terms of performance it does not matter. The network is so much slower in comparison. The transfer cost is significantly higher thus making the generation cost insignificant in comparison. –  Loki Astari Dec 24 '12 at 3:25
show 1 more comment

4 Answers

up vote 11 down vote accepted

As comment points out, it should be done by templates. But if only your two choice is possible. Case 1 will be better. This is the same concept as android inflating layout by xml , or programmaticlly making the UI. Your <br/> is a static content from your html and all your server will be doing is to show it. But if you use php, to execute it, this will be using your servers resources and be computing.

This is how it should be done: index.php:

<?php
include 'header.html';
...
include 'footer.html';  
?>  

header.html and footer.html are templates.

share|improve this answer
    
I have read a book for Kevin Yank which is"PHP & MySQL Novice to Ninja" about something called Controllers and templates. Are these the same thing you were telling me about or are they different? if they are the same how putting the code in different files will make it perform better? –  rashed Dec 24 '12 at 2:17
    
Templates make your website or application more felixable. Do you see how headers and footers or even postes of StackOverflow is the same? They are using the same template and filling it with dynamic data. –  wtsang02 Dec 24 '12 at 2:19
    
What is the main reason behind that? What if we don't do it that way? what will we lose? –  rashed Dec 24 '12 at 2:27
    
Lets look at this. This is the 4th comment of this answer post. If you view this page on source now, you will see "<div><span ...>...</span><a...>...</a>" Imaging hand coding the 4000th comment. Is that possible? or just make this as template and have your server 'add' this when its needed. –  wtsang02 Dec 24 '12 at 2:31
1  
Also @wtsang, you never only have those two choices, you always have a third, run (or learn.) –  Slomojo Dec 24 '12 at 6:36
show 3 more comments

To directly answer your question: Never echo static text or HTML. Leave that outside of your PHP.

<?php echo "<p>Hello World</p>"; // Alway wrong. ?>

<p>Hello World</p>  <!-- Does the same thing, faster, and is more readable. -->

Escaping to PHP is a waste if all you are going to do is pass in static text or static html. All code inside of <?php ?> is sent to PHP to be interpreted. This means your website is slower and you are wasting electricity if you are passing large amounts of static text to PHP for no reason. (Sometimes there is a reason.)

Best practice is to have your logic and grunt work in files without any HTML, only PHP.

The way I like to do this is with an MVC framework. I have pure PHP in the models and controllers, and a mixture of HTML and PHP in the views. You don't need an MVC framework; you could just stick your mixture of HTML in template files, which you then include in your pure PHP files.

Once you have your variables (which don't include HTML in them) created in pure PHP files, you can pass them off to the file with your HTML. There, and only there, is it fine to mix HTML and PHP. But, and this is an important but, when working with files that have HTML, keep the PHP to a minimum.

Luckily, PHP comes with friendly tools to make PHP easier to read when mixed with html.

Alternative Syntax

The best practice is to use regular PHP syntax when writing pure PHP, but the alternative syntax, when mixing PHP and HTML.

In regular PHP files without any HTML:

if ($something) {
  do_something(); // do_something() shouldn't echo or print.
}

This is beautiful for pure PHP, but not ideal when escaping from HTML. In particular, the closing braces are often hard to understand when they show up in big piles of HTML.

It seems, based on your question that you would have written, in a file mixing HTML and PHP, this:

<?php
  if ($something) {
    echo '<p>Hello World.</p>';
  }
?>

For the reasons described above, we want the HTML not to be sent to PHP. We do this like so:

<?php if ($something) { ?>
  <p>Hello World.</p>
<?php } ?>

We got our HTML out of our PHP tags, which is an improvement. But we could go further.

Notice how uninformative the closing brace is? We don't know if it is closing a loop or an if statement. This seems trivial in the above example, but there are often dozens of lines of HTML inside of if/endif inside of a loop/endloop.

The best practice is that in a file mixing PHP and HTML, you use the alternative syntax, which omits opening and closing braces ({ }):

<?php if ($something): ?>
  <p>Hello world.</p>
<?php endif; ?>

Aside from the semantics of the new syntax (: and endif; instead of { and }), you should notice two things:

  1. Again, the HTML and text, while controlled by PHP, is outside of the <?php ?> tags, so it is not interpreted. For the reasons described above, this is good.
  2. This is much more informative than if this were all php including random closing braces (<?php } ?>) closing things that are hard to find where they opened (because they are mixed with a buch of messy looking HTML). Again, imagine a big HTML file with loops and if statements. Specifying what you are closing can clarify a lot.

The same template friendly syntax can be used for loops as well:

<?php foreach ($things as $thing): ?>
  <li><?php echo $thing; ?></li>
<?php endforeach; ?>

Short Tags

Another great tool provided by PHP which, again, you only want to use when mixing PHP and HTML together, is short tags. You might have to turn short tags on in php.ini file. Once turned on, short tags make everything even more readable.

Without short tags, you have to write <?php echo $something; ?> but with short tags you can write <?=$something?> and it will have the exact same result.

When combining short tags and the alternative PHP syntax, you can really write some elegant HTML files, which include PHP elements. Taking our last loop example (just the part inside the loop), short tags allow us to reduce:

<li><?php echo $thing; ?></li>

to

<li><?=$thing?></li>

which is much more readable.

Could we go further? Yes. Using various templating systems you can do things like:

<li>{thing}</li>

Which is amazingly readable. Templating systems, however, are way outside the scope of the original question (which I left a while ago anyway).

share|improve this answer
3  
+1 For being good advice for everyone. Alternate control syntax and short tags are immensely important for getting started with templates and separation of logic from presentation. –  MobyD Dec 24 '12 at 12:44
    
Short tags should be used with caution. If you are building code that will be reused, you can't guarantee that the short_open_tag directive will always be turned on. PHP 5.4 makes the <?=$thing?> available all the time, even when short_open_tag is disabled. Also, short_open_tag is defaulted to off to prevent conflicts with XML. –  Chris Dec 24 '12 at 17:46
1  
+1 for showing the different alternatives, progressing to the best answer. –  Tola Odejayi Jan 2 '13 at 3:48
add comment

It is generally considered bad form to output HTML code from PHP. There are several reasons for this, but the main one is that it is easier, especially in the long run, to maintain code if the HTML and PHP code is separated.

It is just like HTML, CSS and Javascript; it is just much easier and more practical to keep it separate.

Technically, however, it makes absolutely no difference how you output stuff. To PHP it is just bytes in a row.

share|improve this answer
2  
It does make a difference. <?php echo 'hello'; ?> gets passed to PHP. hello does not get passed to PHP. Anything that gets passed to PHP gets converted to bytecode then interpreted. This takes time, processing power, and electricity. –  Ted Dec 25 '12 at 1:04
add comment

You're learning, forget about performance in PHP pages. Instead, choose the way that is easiest to read.

Looking at your two examples the second one is most definitely easiest to read, though I think that's because of the spacing you've used. You say you're looking to develop good habits from the start, I think your time can be better spent by making your code read well. This might mean rewriting a section several times until you're happy with it.

If you're really keen on the behind-the-scenes, I'll have a go at explaining what happens with static content in a PHP page. One of the first things is to "parse" the entire page into executable code (like you see between <?php ?> tags). One part of this is to turn any static text into an echo.

So this:

<?php echo "Hello World"; ?>
<br />
<?php echo "Welcome"; ?>

is transformed into something like:

echo "Hello World";
echo "<br />";
echo "Welcome";

There's a very small cost associated with the parsing, but no difference in executing the resulting code. If you're using a PHP accelerator the parsing is only done once and then cached, so you would see no performance difference after the first page load.

Remember: easy to read!

share|improve this answer
    
I Disagree. It's not just about the performance, it is actually about learning. It is not a good advice to learn a wrong practice. –  Isaac Dec 30 '13 at 9:10
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.