Dropping in and out of PHP for HTML code or ECHO/PRINT?

What is the preferred method for writing code? Is it considered best to stay in PHP and use ECHO to output HTML code where needed? Or is it better to drop out of PHP and just code straight HTML code?

For example, when processing a WHILE loop, maybe you want to make a table out of the results and so need to place your table cell end and start code. Which is the recommended method? Drop in and out of PHP or ECHO?

I understand the keeping the code separate, I am referring to the times when you NEED to embed them together or assemble a string.

Thanks!

Greg

If you’re running through a loop you can’t drop in and out from PHP to HTML and back again.

Instead you bolt all the HTML together for your table inside PHP as a string, then echo it
all out at once.

Notice the .= this appends (joins) the string together into one long one.

<?php
foreach (array('one', 'two', 'three', 'four') as $output) {
    $dump_to_screen .= $output." - ";
}
?>


<!DOCTYPE>
<head></head>
<body>
<?php echo  $dump_to_screen;?>
</body>
</html>

If you’re running through a loop you can’t drop in and out from PHP to HTML and back again.

Technically that’s not true…


<ul><?php
$a=0;
foreach (array('one', 'two', 'three', 'four') as $output) {
    $a=$a+1;?>
    <li>
    <? echo $a. '] ',$output,'<br>';?>
    </li>
<? } ?> </ul>

works… but it’s just ugly and confusing code.

I don’t actually know if there is noticeble a performance hit for dropping in and out of PHP. But I think what ever it is can easily be worth the weight of readable code or easily modifiable templates.

If other words, what I did above is possible, but not recommended ( more for readability’s sake than performance) On the other hand…

<title><? PageTitle()?</title>

Or even Long applications of heredoc are not a bad thing. Also, dropping out of PHP makes it easier to preserve your formatting and indenting. I find it quite valuable when debugging my output (HTML) .

Output:

I “prefer” to be able to:

glance
understand
easily edit the script

value: 0
value: 1
value: 2
value: 3
value: 4
value: 5
footer goes here

Source:



<table summary='#'  style='text-align:left'>
  <thead>
    <tr>
      <th>
        I   "prefer" to be able to:
        <ul>
          <li>glance</li>
          <li>understand</li>
          <li> easily edit the script</li>
        </ul>
      </th>
    </tr>
  </thead>

  <?php for($i2=0; $i2<=5; $i2++) { ?>
    <tr>
      <td>
        <?php echo 'value: '.$i2;?>
      </td>
    </tr>
  <?php } ?>

  <tfoot>
     <tr>
       <td>footer goes here</td>
     </tr>
   </tfoot>

</table>

dresden_phoenix:

So would you rather have: (please disregard any coding/typos, think this gets the point across)
<?php
echo “<ul>”;
$a=0;
foreach (array(‘one’, ‘two’, ‘three’, ‘four’) as $output) {
$a=$a+1;
echo “<li>”;
echo $a. ‘] ‘,$output,’<br>’;
echo “</li>”;
}
echo “</ul>”;
?>

Personally I like John_Betong’s style of code myself. It’s similar to dresden_phoenix original code, but for whatever reason seems a bit cleaner. I realize depending on what you are action you are actually performing sometimes it could be quite ugly. However, (especially if you are using an editor with code highlighting) I think the potential to have that point out a coding error is more likely.

Greg

Based on all the major frameworks, the preferred method is the alternative syntax. It’s very similar to John_Betong’s code. Here’s how it would look:

<table summary='#'  style='text-align:left'>
  <thead>
    <tr>
      <th>
        I   "prefer" to be able to:
        <ul>
          <li>glance</li>
          <li>understand</li>
          <li> easily edit the script</li>
        </ul>
      </th>
    </tr>
  </thead>

  <?php for ($i = 0; $i <= 5; $i++): ?>
    <tr>
      <td>
        value: <?php echo $i ?>
      </td>
    </tr>
  <?php endfor ?>

  <tfoot>
     <tr>
       <td>footer goes here</td>
     </tr>
   </tfoot>

</table>

Hmm, alternative syntax is an interesting adjustment, but the biggest change I see between the two styles is you change the opening { to : and the closing } to endwhatever. More verbose, but arguably easier to code trace. Seeing what a particular closing } is for is much easier using the alternative syntax method, at the expense of slightly expanded file sizes (albeit the change is negligible). I’ll keep that method in mind and try both and I guess just see what I settle into.

Thank you for the feedback!

Greg

GH,
Basically I was saying what Jeff just said… tho I skipped the alternative format. Shame on me! I got lost in trying to say that you CAN HTML withn a PHP loop, you just need to take care to keep your code readable. Gains in readability far outweigh ALMOST any speed gain of dropping in and out of PHP. So I FAVOUR dropping in and out for the reason John listed AND the additional reason that dropping out of PHP preserves your HTML formatting easily ( indents, new lines etc) …

I really should have written this as well to keep my example consistent.


<ul>
  <?php for($i2=1,$th=array('st','nd,'rd','th'); $i2<=15; $i2++) : ?>
        <li>I am the<?php echo $i2, (($i2)<3)? $th[$i2-1]:$th[3] );?> list item<li>
  <?php endfor ?>  
</ul>

I just added two asides tho.

  1. Use common sense, For small scripts or simple templates it makes little difference. I want to keep my samples sort so the scripts/ mock templates are short and basic. It may not always be the smart thing to do.

This is NOT clever at all:


<div class="article">
  <?php while($hasNextP()) : ?>
        <p>$getNextP();</p>
  <?php endwhile ?>  
</div>

  1. you gain a small speed boost using singe quote for non parsed text, also you can eco with “,” instead of “.” : eg.: echo 'I am static text ',$bar, ‘I was joined with a comma instead of a dot because its faster than concatonating with a period’," variable $a and newlines need tobe parsed
    ";

Some may also argue that multiple echo statements would negate the performance gains from avoiding dropping in/out of PHP.

I can gain over 100%, double the execution speed by not using HTML. Great to have further speed tips from dresden_phoenix as well though.

Take a look at this page to see how I benefit from not using it.

Basically I only output the very first page with HTML. All subsiquent pages get outputed using JavaScript unless the request is sent by POST. This way I can avoid loading the HTML for the common content for every page load

…as long as every person who uses your site enables javascript. Otherwise they’re screwed.

Is that directed at me StarLion? I think you might want to read a bit more in to it. Or Compare my site with javascript on/off. Works exactly the same way, apart from server, network and client do more work without javascript.

Have a look in IE with network capturing turned on. It might help see what’s happening. :slight_smile:

Oh, and the clock will show the server time rather than local.

Sorry to be critical, Markdidj, but my views on this are: 1) It looks like run-of-the-mill ajax. This isn’t exactly a breakthrough idea. 2) Even though ajax may yield performance improvements, it’s unrelated to the topic of this thread. And 3) I agree with logic_earth from the other thread. The code seems awfully messy and hard to understand.

  1. It predates Ajax
  2. It predates Ajax
  3. Why I don’t step in and out of HTML
  4. Whitespace was stripped.

I don’t find it messy at all. I find it easier to read when I’m not stepping in and out of HTML. And at over 100% server execution and bandwidth capacity improvements even if it were messy it’s worth the bonus!

I think the biggest take-away is

The OP was looking for was a way to separate their HTML from the PHP code, or at least good practices. The problem is your implementation still groups the two together for the content portion, albeit the header and footer may be separate, the content remains a mixture of PHP and HTML output (or at least could).

@GHicks,

There are a variety of ways you can go about this, many listed above, others a bit more complicated (in fact, I’ve been toying with an idea on my latest project, but it isn’t anywhere near ready to be shown outside of my test environment and still needs some major refactoring). Personally I like MVC approaches, where separating the content/design from the code is very well indicated.

Where I believe you are coming from, is what if the content needs to loop through a data structure, how do I make that clean? That is a process I am working through right now, you can kind of consider it as a sub-view to a view. So the view being your cart for example, header, buttons, etc, the sub-view being an individual item that is listed in the cart, and the cart view just calls the sub-view to provide its’ output (this is just a very high level overview of the idea, but hopefully shows the process).

Bet it’s a nightmare to debug and work with though.

I’d be ripping my hair out if I inherited a code base like that.

But you know you could just cache the common html quite easily?

Also, upon re-reading your comment here, it appears to just be ajax? Not sure how you’re measuring the 100% speed increase either. Not unless you had a massive amount of html to load outside of the content you’re swapping via javascript/ajax. Even then, as I say, you could do this without the pain by simply caching those common html elements.

Well, I’m not here for defensive arguments. If you can’t see the benefits I’m not here to drill it in.

I’ll step out from here.

Not being funny, but if the code is messy and inflexible then the speed benefit starts to matter less and less. Also, the kind of speed benefits you are likely talking about are probably measured in milliseconds, in which case, unless you’re facebook, the supposed benefits are outweighed by the negativity of difficult to maintain code. Just my three penneth.