-1

Basically I was just wondering what is the difference between this two statements in HTML script:

<?php if($something == null) { ?>
  <div>This is just HTML code</div>
<?php } ?>

and:

<?php if($something == null) {
  echo '<div>This is just HTML code passed from PHP</div>';
} ?>

Is there a preferred way?

Jay
  • 57
  • 3
  • 9
  • I think both are correct – Lal Aug 01 '15 at 17:06
  • I think both are terrible, because you're mixing front- and backend. There should be a clear and clean seperation. Perhaps you may investigate into a PHP template engine, i.e. [Smarty](http://www.smarty.net/). – Mischback Aug 01 '15 at 17:08
  • Nope no preferred objective way, Use either of them you like. Its as subjective as it gets. – Hanky Panky Aug 01 '15 at 17:08

4 Answers4

1

No, there's no difference. But there's a third, better syntax that PHP provides for templating:

<?php if($something == null): ?>
  <div>This is just HTML code</div>
<?php endif ?>

This way you can avoid stray } brace errors since this is easier to read. for and foreach also support this syntax.

Anonymous
  • 11,740
  • 3
  • 40
  • 50
1

You must try to write it as clean as possible. And preferred one is the neater one. Now what about this:

<?PHP if($something == null): ?>
    <div>This is just HTML code</div>
<?PHP endif; ?>
Hossein Shahsahebi
  • 6,348
  • 5
  • 24
  • 38
  • Thank you for the advice, and thank you for answering about CodeIgniter. I apologize for deleting my comment but I still happened to see yours. I up voted you so that you were at least at 0. – Jay Aug 01 '15 at 17:25
  • You're welcome dude :). To prevent down voting please search first. It has bad effect ;) – Hossein Shahsahebi Aug 01 '15 at 17:26
0

Both code blocks work similarly.

There is NO difference in the output.

However, the 1st method is preferred as it omits the unnecessary string handling which becomes tedious in situations where " and ' are used in the HTML code.

It also keeps the HTML and PHP code separate which makes it easier to maintain.

The following code should be preferred.

<?php if($something == null) { ?>
  <div>This is just HTML code</div>
<?php } ?>
Shrinivas Shukla
  • 4,325
  • 2
  • 21
  • 33
0

Both gives the same output, however,

This is the not the preferred and unclear type of code: <?php if($something == null) { ?> <div>This is just HTML code</div> <?php } ?>

whereas,the second code is simple to read and understand and usually used when you have to print some dynamic php content in between html code.