PHP in HTML
PHP can be used easily in HTML. For do that the file should be a .php file, not a .html one. We will learn some awesome PHP tricks in this chapter.
Adding Dynamic Date to HTML Pages
Many websites show the current year on their website with their logo. But, if you have static HTML pages, you have to update them every year. To prevent that, create a PHP file like following.
PHP Date
<html>
<head>
<title>Date</title>
</head>
<body>
Today is <?= date('jS \o\f F Y') ?>
<br><br>
<strong>Year with logo:</strong> <br>
Hyvor Inc. © <?= date('Y') ?>
</body>
</html>
Run Example ››We have used the shorthand echo statement in the above example.
Conditionals with HTML
This is a cool trick in PHP. We can show different HTML content according to conditionals in PHP. Let's learn it by an example!
Conditionals with HTML
<?php
$user = 'admin';
?>
<?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 ››Note the semicolon : before the PHP closing tags. And, unlike normal if statements, endif; statement should be there to specify the ending of the conditional.
For Loops with HTML
For Loops with HTML
<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 ››Array to Table
We can convert a PHP array to a table with foreach loops, using the above technique.
Array to Table
<?php
$array = [
['Joe', '[email protected]', 24],
['Doe', '[email protected]', 25],
['Dane', '[email protected]', 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 ››