← Back to PHP Course | Chapter 15: Web Development | Lesson 1 of 12

PHP with HTML & CSS

Mixing PHP with HTML

PHP tags can be embedded directly inside an HTML file; the server executes any PHP it finds and replaces those blocks with their output before the finished HTML is sent to the browser.

Example: Mixing PHP with HTML

php
<?php $name = "Alice"; ?>
<h1>Welcome, <?php echo $name; ?></h1>

Outputting CSS Dynamically

Because PHP runs before the page reaches the browser, you can generate CSS values dynamically -- like setting a background color from a database-stored theme preference -- by echoing them straight into a style attribute or block.

Example: Outputting CSS Dynamically

php
<?php $themeColor = "darkblue"; ?>
<div style="background-color: <?php echo $themeColor; ?>;">Themed box</div>

Conditional HTML Rendering

Wrapping HTML in if-else blocks lets a template show or hide entire sections based on server-side conditions, like displaying an admin menu only when the logged-in user has the right role.

Example: Conditional HTML Rendering

php
<?php $isAdmin = true; ?>
<?php if ($isAdmin): ?>
  <nav>Admin Menu</nav>
<?php else: ?>
  <nav>Regular Menu</nav>
<?php endif; ?>

Looping HTML Elements

A foreach loop around a chunk of HTML is the standard way to render a repeating structure -- like table rows or product cards -- once per item in an array, instead of writing out each one by hand.

Example: Looping HTML Elements

php
<?php $products = ["Book", "Pen", "Notebook"]; ?>
<?php foreach ($products as $product): ?>
  <div class="product-card"><?php echo $product; ?></div>
<?php endforeach; ?>

Shorthand Echo Tags

The shorthand tags <?= $value ?> are equivalent to <?php echo $value; ?> but far less noisy when a template needs to print dozens of small values throughout a page.

Example: Shorthand Echo Tags

php
<?php $price = 19.99; ?>
<p>Price: $<?= $price ?></p>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.