Developer
PHP
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP VariablesPHP ConstantsPHP OutputPHP Data TypesPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

PHP in HTML

PHP is designed to interact with 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 about awesome PHP tricks in this chapter.

Adding Dynamic Date to HTML Page

Many websites shows the current year in 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 <?php echo date('jS \o\f F Y') ?>

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

Run Example ››

Conditionals with HTML

This is a cool trick in PHP. We can show HTML according to conditionals in PHP. Let's learn it by a 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 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 ››
Advertisement
0
93