Although it's okay to use <?php echo when using php to generate an HTML output, there is a better way. For example, consider the code below where echo statement was used to generate an html output.
When the html output gets complex, putting all the html tags inside the echo statement could lead to typing mistakes. It also makes it hard to visualize if you're closing all the necessary html tags properly.
Best practice
Instead of using php echo to print out a bunch of html, it's better to format your code as follows:
Best Practice - echo
Although it's okay to use <?php echo when using php to generate an HTML output, there is a better way. For example, consider the code below where echo statement was used to generate an html output.
<?php $users = array( array('first_name' => 'Michael', 'last_name' => 'Choi'), array('first_name' => 'John', 'last_name' => 'Supsupin'), array('first_name' => 'Mark', 'last_name' => 'Guillen'), array('first_name' => 'KB', 'last_name' => 'Tonel') ); ?> <html> <body> <div class='content'> <?php echo "<h1>".count($users)." Users</h1>"; foreach($users as $user){ echo "<p>".$user['first_name'] ." " . $user['last_name'] . "</p>"; } ?> </div> </body> </html>
When the html output gets complex, putting all the html tags inside the echo statement could lead to typing mistakes. It also makes it hard to visualize if you're closing all the necessary html tags properly.
Best practice
Instead of using php echo to print out a bunch of html, it's better to format your code as follows:
<?php $users = array( array('first_name' => 'Michael', 'last_name' => 'Choi'), array('first_name' => 'John', 'last_name' => 'Supsupin'), array('first_name' => 'Mark', 'last_name' => 'Guillen'), array('first_name' => 'KB', 'last_name' => 'Tonel') ); ?> <html> <body> <div class='content'> <h1><?= count($users) ?> Users</h1> <?php foreach($users as $user) { ?> <p><?= $user['first_name']?> <?= $user['last_name']?></p> <?php } ?> </div> </body> </html>
The difference may not seem very much but when the html gets a lot more comp...