PHP Indent (my coding standards)

I really like it when my HTML is perfectly indented.

Same thing with my PHP.

I will show you how to do both in the same script.

Although some people don't like them, I like the standard loops and ?> and <?php tags.

To have perfect indentation with both the HTML and PHP code, some rules have to be followed.

PHP tags

An interesting fact about the ?> tag is that PHP will eat the following newline.

So if your opening PHP tag (<?php) starts the line, the block will not leave anything in the HTML.


I like to think that there are two parallel indentations in every PHP script. The HTML indentation and the PHP indentation.

I also like to put the PHP indentation not before the <?php tag but after.

This way, <?php always starts a line and this prevents the echoed HTML from having weird spacing all over the place.

On every if/for/foreach, I indent the PHP.

In HTML, I follow other rules. I like it when some tags stay in the same line instead of having lots of indentation.

Like this :

<form><input /></form>

In PHP, I go like this :

<?php if (true): ?>
<?php	if (true): ?>
<?php		if (true): ?>

<?php		endif: ?>
<?php	endif: ?>
<?php endif: ?>

Notice how every <?php tag starts the line. This means that they are all removed from the HTML.

When indenting my HTML code, I indent it like the PHP is not there.

Recently at work, I had to take a three level deep associative array and render in a grouped table with lots of rowspans.

It went like this :

<table border=1 cellpadding=5>
<?php foreach ($all as list($nom, $table)): $i = 0; ?>
		<th rowspan="<= htmlspecialchars(array_sum(array_map('count', $table))) ?>"><?= htmlspecialchars($nom) ?><th>
<?php	foreach ($table as $at => $ra): ?>
<?php		if ($i): ?>
<?php		endif; ?>
		<td rowspan="<= htmlspecialchars(count($ra)) ?>"><?= htmlspecialchars($at) ?><td>
<?php		foreach ($ra as $j => $r): ?>
<?php			if ($j): ?>
<?php			endif; ?>
		<td><?= htmlspecialchars($r) ?><td>
<?php		endforeach; ?>
<?php	++$i; endforeach; ?>
<?php endforeach; ?>

It may seem a little cahotic to the untrained eye, but everything here is exactly how I like it.

Not only is the PHP perfectly indented, but the generated HTML is also perfectly indented.