PHP with HTML & CSS
In this page:
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 $name = "Alice"; ?>
<h1>Welcome, <?php echo $name; ?></h1>
Login to try C/C++/Java/PHP code in the editor
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 $themeColor = "darkblue"; ?>
<div style="background-color: <?php echo $themeColor; ?>;">Themed box</div>
Login to try C/C++/Java/PHP code in the editor
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 $isAdmin = true; ?>
<?php if ($isAdmin): ?>
<nav>Admin Menu</nav>
<?php else: ?>
<nav>Regular Menu</nav>
<?php endif; ?>
Login to try C/C++/Java/PHP code in the editor
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 $products = ["Book", "Pen", "Notebook"]; ?>
<?php foreach ($products as $product): ?>
<div class="product-card"><?php echo $product; ?></div>
<?php endforeach; ?>
Login to try C/C++/Java/PHP code in the editor
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 $price = 19.99; ?>
<p>Price: $<?= $price ?></p>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: