PHP/HTML Mixed Code Indentation Practices
When integrating PHP and HTML code, how should one approach indentation? Should the focus be on the proper formatting and readability of the mixed code itself or on the correct indentation of the resulting HTML output?
To illustrate, consider a foreach loop generating table rows:
Indentation Prioritizing PHP/HTML Mix Readability:
<table> <?php foreach ($rows as $row): ?> <tr> <?php if ($row->foo()): ?> <?php echo $row; ?> <?php else: ?> Something else <?php endif; ?> </tr> <?php endforeach; ?> </table>
In this example, the PHP and HTML are indented separately to maintain the readability of the mixed code.
Indentation Prioritizing HTML Output Correctness:
<table> <?php foreach ($rows as $row): ?> <tr> <?php if ($row->foo()): ?> <?php echo $row; ?> <?php else: ?> Something else <?php endif; ?> </tr> <?php endforeach; ?> </table>
Here, indentation follows the structure of the outputted HTML to ensure its correct rendering.
The optimal indentation strategy depends on the developer's preference. However, the recommended approach is to indent the PHP and HTML independently, ensuring their correctness in their respective source forms. This practice leads to cleaner and more maintainable code:
<table> <?php foreach ($rows as $row): ?> <tr> <?php if ($row->foo()): ?> <?php echo $row; ?> <?php else: ?> Something else <?php endif; ?> </tr> <?php endforeach; ?> </table>
The above is the detailed content of PHP/HTML Mixed Code: Indent for Readability or Output Correctness?. For more information, please follow other related articles on the PHP Chinese website!