Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php echo vs open&close tag

Tags:

php

echo

tags

Just to clarify: The issues "echo vs print" and "double quotes vs single quotes" are perfectly understood, this is about another thing:

Are there any reasons why one would prefer:

echo '<table>';   
foreach($lotsofrows as $row)
{
    echo '<tr><td>',$row['id'],'</td></tr>';   
}
echo '<table>';

over:

<table><?php
       foreach($lotsofrows as $row)
       { ?>
           <tr>
              <td><?php echo $row['id']; ?></td>
           </tr><?php
       } ?>
</table>

would either one execute/parse faster? is more elegant? (etc.)

I tend to use the second option, but I'm worried I might be overlooking something obvious/essential.

like image 903
Migs Avatar asked Sep 08 '09 14:09

Migs


People also ask

What is a PHP echo?

PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc. Some important points that you must know about the echo statement are: echo is a statement, which is used to display the output. echo can be used with or without parentheses: echo(), and echo.

Does echo work in PHP?

The PHP echo StatementThe echo statement can be used with or without parentheses: echo or echo() .

Do I need to close <? PHP?

It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.

What is difference between echo and return in PHP?

Echo is for display, while return is used to store a value, which may or may not be used for display or other use.


2 Answers

Benefits of first one

  • Easier to read
  • ???

Benefits of second one

  • WYSIWYG is possible
  • HTML Code Completion/Tag-Matching possible with some IDEs
  • No escaping headaches
  • Easier for larger chunks of HTML

If I have a lot of HTML in a given PHP routine (like an MVC view) then I definitely use the 2nd method. But I format it differently - I strictly rely on the tag-like nature of PHP's demarcations, i.e., I make the PHP sections look as much like HTML tags as I can

<table>
  <?php foreach($lotsofrows as $row) { ?>
  <tr>
    <td><?php echo $row['id']; ?></td>
  </tr>
  <?php } ?>
</table>
like image 190
Peter Bailey Avatar answered Oct 19 '22 14:10

Peter Bailey


I agree with Peter Bailey. However, in views I use the alternative syntax for statements, and much prefer short tags (particularly for echoing). So the above example would instead read:

 <table> 
  <? foreach($lotsofrows as $row): ?>
  <tr>
    <td><?= $row['id']; ?></td>
  </tr>
  <? endforeach; ?>
 </table>

I believe this is the preferred standard for Zend Framework.

like image 26
voidstate Avatar answered Oct 19 '22 15:10

voidstate