4

I was always curious, is there any significant advantage or disadvantage of writing php inside html or vice versa

example:

echo '<ul>'
foreach ($items as $item)
{
    echo "<li>$item</li>";
}
echo '</ul>

As opposed to:

<ul>
<? foreach($items as $item): ?>
    <li>$item</li>
<? endforeach; ?>
</ul>

Since these essentially generate the same thing, when would you actually use one over the other?

hakre
  • 193,403
  • 52
  • 435
  • 836
clifford.duke
  • 3,980
  • 10
  • 38
  • 63
  • http://stackoverflow.com/questions/5295473/what-are-the-advantages-of-seperating-php-and-html might help you. – Vinay Nov 03 '12 at 04:13
  • 1
    if it's an even split between html and php code, either's fine. If you've got 5000 lines of html and 1 single php echo, then do php-inside-html. 5000 lines of php and a single line of html? html-in-php. It comes down to your preferences and maintainability – Marc B Nov 03 '12 at 04:14
  • http://php.net/language.basic-syntax.phpmode http://php.net/control-structures.alternative-syntax http://php.net/faq.html and: http://stackoverflow.com/questions/1100354/how-can-i-echo-html-in-php might be insightful, too. – hakre Nov 03 '12 at 11:08

4 Answers4

5

Functionally they are the exact same and won't have an appreciable affect on performance, if any. It comes down to personal preference and readability - if one is clearer than the other and will be easier for others (or the future you) to understand, go with that one.

doublesharp
  • 26,888
  • 6
  • 52
  • 73
2

I personally find it better to use the latter if you actually have PHP in a mostly HTML file. The clear opening/closing tags match up visually with HTML easier. I find it can be hard to line up curly braces visually.

As an example, in the case of a MVC framework I would use the first way of outputting things in a controller or model context, while the second way in my view files. Some templating languages like smarty have similar looking constructs.

ie:

{ if [condition] }
{ /if }
Shane Fright
  • 385
  • 1
  • 9
  • That's exactly what I was thinking, the latter would be perfect in a template environment whereas the other would be better in the logic portion of the web application – clifford.duke Nov 03 '12 at 04:22
1

The first one echoes meaningless strings from the IDE's point of view, whereas the latter one is a mix of HTML and PHP and will be handled properly by your editor. In other words, it's better to actually separate HTML from PHP as it allows your editor to parse HTML and provide some usefull features like syntax validation or autoclosing of HTML tags.

Crozin
  • 43,890
  • 13
  • 88
  • 135
0

basically php is a server side scripting and html is client side scripting. So if it is php inside html then it generates faster response and you can format a better view. However for some scenario you might have to consider the other case for developing.

Sahil Jariwala
  • 243
  • 2
  • 5
  • 19