How to properly indent PHP/HTML mixed code? [closed]
When mixing PHP and HTML, what is the proper indentation style to use? Do I indent so that the outputted HTML has correct indentation, or so that the PHP/HTML mix looks properly formatted (and is thus easier to read)?
For example, say I have a foreach
loop outputting table rows. Which one below is correct?
PHP/HTML mix looks correct:
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
Outputted HTML looks correct:
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
I've found that when I run into this situation (quite frequently), I don't have a standard style to use. I know that there may not be a "correct" answer, but I'd love to hear thoughts from other developers.
Solution 1:
The PHP and the HTML should each be indented so that they are correct with respect to themselves in source form, irrespective of each other and of outputted form:
<table>
<?php foreach ($rows as $row): ?>
<tr>
<?php if ($row->foo()): ?>
<?php echo $row ?>
<?php else: ?>
Something else
<?php endif ?>
</tr>
<?php endforeach ?>
</table>
Solution 2:
I often pondered this question too, but then I realized, who cares what the HTML output looks like? Your users shouldn't be looking at your HTML anyway. It's for YOU to read, and maybe a couple other developers. Keep the source code as clean as possible and forget about what the output looks like.
If you need to debug the output, use Chrome Developer Tools, Firebug, or even F12 Tools.
Solution 3:
I generally put opening php tags at the beginning of the line, but indent whatever is inside the tags to match the html formatting. I don't do this, however, for simple echo statements since I use short-open tags. I think it makes simpler it when browsing through the file to find all the declarations.
<table>
<? foreach ($foo as $bar): ?>
<tr>
<? foreach ($bar as $baz): ?>
<td><?=$baz?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
Solution 4:
- Direct answer to your question: If you need to read the HTML output often, it might be a good thing to output well indented HTML. But the more common case will be that you need to read your php source code, so it is more important that the source is easily readable.
- Alternative to the two options you mentioned: See chaos' or tj111's answer.
- Better still in my opinion: Don't mix HTML and php, use a template engine instead.