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.
Spacing and indentation should be consistent throughout your code. Many developers choose to use 4-space or 2-space indentation. In PHP, each nested statement (e.g., a statement following a "{" brace) should be indented exactly once more than the previous line's indentation.
You can indent elements by moving them two spaces to the right. This will make your code more readable by other developers and shows the relationship between the child and parent HTML elements.
PHP is whitespace insensitive PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row. one whitespace character is the same as many such characters.
No. HTML code does not need to be indented, and all browsers and search engines ignore indentation and extra spacing. However, for any human reader, it's a good idea to indent your text because it makes the code easier to scan and read.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With