Using PHP in HTML

Hi, dear 000webhost users,

Today we will be discussing some cool uses of PHP in HTML.

1. Adding Dynamic Date to HTML Page

Have you seen some websites show the current year on their website? If they had static HTML pages, they have to update those pages yearly. You can use PHP to add a dynamic date. So, once you write the page, you don’t need to update it again.

<html>
<head>
	<title>Date</title>
</head>
<body>
Today is <?php echo date('jS \o\f F Y') ?>

<br><br>
<strong>Year with logo:</strong> <br>
Company Inc. &copy; <?php echo date('Y') ?>
</body>
</html>

Run Example >>

2. Serving Dynamic HTML according to PHP conditionals

This is a pretty cool trick in PHP. Assume that you need to display a message according to the value of a PHP variable. This is the way to do that.

<?php
$user = 'admin'; // change this as you need
?>

<?php if ($user === 'admin') : ?>

<p>You are an admin.</p>
<p>You can access the console.</p>

<?php elseif ($user === 'developer') : ?>

<p>You are a developer.</p>
<p>You can access the developer console</p>

<?php else : ?>

<p>You are a normal user.</p>

<?php endif; ?> 

Run Example >>

3. HTML lists with PHP (prevents code re-writing)

<html>
<head>
	<title></title>
</head>
<body>

<?php for ($i = 1; $i < 6; $i++) : ?>

<li>List Item <?php echo $i ?></li>

<?php endfor; ?>

</body>
</html>

Run Example >>

4. Array to Table

A PHP array can be converted to a table simply like following.

<?php
$array = [
	['Joe', 'joe@hmail.com', 24],
	['Doe', 'doe@hmail.com', 25],
	['Dane', 'dane@hmail.com', 20]
];

?>

<table>
	<tr>
		<th>Name</th>
		<th>Email</th>
		<th>Age</th>
	</tr>

<?php foreach ($array as $person) : ?>

<tr>
	<?php foreach ($person as $detail) : ?>
		<td><?php echo $detail ?></td>
	<?php endforeach; ?>
</tr>

<?php endforeach; ?>


</table>

Run Example >>

I hope you enjoyed this tutorial. Also, this tutorial is available on my website.

Thank you for reading. :smile:

5 Likes