Inserting PHP into HTML can be tricky if you have a lot of code to address. By working backwards and step-by-step we can hopefully avoid some common oversights – such as forgotten closing tags, braces, or semicolons – when writing our code.
In this example, we want to use PHP to conditionally assign a class of “on” if our page section is “Shirts.”
Here’s the final bit of code that we’ll end up with:
<li class="shirts <?php if ($section == "shirts") { echo "on"; } ?>"><a href="shirts.php">Shirts</a></li>
Step 1 – Begin with the plain HTML that we want:
<li class="shirts on"><a href="shirts.php">Shirts</a></li>
Step 2 – Add PHP opening and closing tags around our “on” class:
<li class="shirts <?php on ?>"><a href="shirts.php">Shirts</a></li>
Step 3 – Add an echo
statement around our “on” class:
<li class="shirts <?php echo "on"; ?>"><a href="shirts.php">Shirts</a></li>
Step 4 – Add the conditional statement if ($section == "Shirts") {}
around our echo statement:
<li class="shirts <?php if ($section == "Shirts") { echo "on"; } ?>"><a href="shirts.php">Shirts</a></li>
That’s it! No more forgotten closing tags, braces, or semicolons!