Why separate PHP from HTML in a code as much as possible?

Twice now that I have asked and was responded that I should separate PHP from HTML in codes as much as possible. Instead of using:

<?php
echo "<p>The value of x is $valuex greater.</p>";
?>

That I should use:

<p>The value of x is <?php echo $valuex; ?> greater.</p>

Is there any difference I should know other than the format?

Upvotes: 0

Views: 548

Answers (7)

David Jones
David Jones

Reputation: 10229

One of the unique things about PHP is that it serves the purpose of both a server-side language and a templating language. Ideally, your code would be separated into controllers and views, where your controllers are pure PHP (without any HTML) and your views are mostly HTML (with minimal PHP). When you're writing a controller, PHP is just like any other server-side language. But when you're writing a view, PHP becomes a templating language, in which case HTML should rule.

Another good reason to separate the two is syntax highlighting. In your first example, most editors wouldn't realize that the text within the string is actually HTML, so they wouldn't know to apply syntax highlighting. This means your code will likely be harder to read than it could be, making life difficult for subsequent developers.

Upvotes: 1

Rikesh
Rikesh

Reputation: 26441

You need echo in second one,

<p>The value of x is <?php echo $valuex; ?> greater.</p> 

Or simply,

<p>The value of x is <?=$valuex ?> greater.</p>

Read: What's the best way to separate PHP Code and HTML?. Also read Escaping From HTML.

Upvotes: 1

fiskeben
fiskeben

Reputation: 3467

It's much easier to maintain your code, both HTML and PHP, when separating them.

Upvotes: 0

Fabian Schneider
Fabian Schneider

Reputation: 365

The reason for this is that frankly you'll want to always be as flexible as possible. However, mixing your php with html means that your php-core is mixed up with your template, thus you'll have an a lot harder time maintaining, altering & providing different templates/languages etc. Thus always keep it apart.

Upvotes: 0

GautamD31
GautamD31

Reputation: 28753

On the first one change the syntax like

<?php
   echo "<p>The value of x is ".$valuex." greater.</p>";
?>

and in the second one change to echo the value like

<p>The value of x is <?php echo $valuex; ?> greater.</p>

But both the notations are same,and work same

Upvotes: 0

VCNinc
VCNinc

Reputation: 757

The output will be the same in both cases.

The first example is PHP outputting HTML code The second example is HTML code with PHP inside it The "Ideal" example is this:

<p>The value of x is <?=$valuex?> greater.</p>

Upvotes: 0

Vijaya Pandey
Vijaya Pandey

Reputation: 4282

The difference is:

<?php $valuex = 6; ?>

<p>The value of x is <?php echo $valuex; ?> greater.</p>

Here you need to echo only php variable part.

<?php
echo "<p>The value of x is $valuex greater.</p>";
?>

Here you need to echo whole part.

Upvotes: 1

Related Questions