A better way to write HTML code inside PHP

While making a web application with PHP, we often need to write HTML tags inside PHP file to print out a few results in form of HTML. We can do this task in many different ways. Some of methods I’ve been used below,

Softmastx
1 min readJan 20, 2020

Echo or Print the classic way.

Almost every developer uses this style for example,

<?php 
$name = "Softmastx";
echo "<h1>Hello User, </h1> <p>Welcome to {$name}</p>";
?>

or

<?php
$array = array(1, 2, 3, 4);
?>
<table>
<thead><tr><th>Number</th></tr></thead>
<tbody>
<?php foreach ($array as $num) : ?>
<tr><td><?= htmlspecialchars($num) ?></td></tr>
<?php endforeach ?>
</tbody>
</table>

A better way!

Use ?>…<?php inside normal open and close tag.

<?php
$name = "Softmastx";
?> <div class="profile profile-user">
<h1>Hello User, </h1>
<p>Welcome to <?php echo $name;?></p>
</div>
<?php?>

Instead of getting code in green, you still have code highlighting!!!

--

--