Codecademy Logo

PHP and HTML

Dynamic Webpages using PHP

PHP is a server scripting language. This server side code can be used to fill out HTML templates in order to create a complete HTML document for a visitor. This finished document is called a dynamic webpage.

Dynamic PHP webpages can deliver a custom set of assets to each visitor, unlike static pages which deliver the same set of assets to everyone.

Embedding PHP Code

PHP can generate HTML when saved as a file with a .php extension. These files must always start with the tag <?php (closing tag is optional).

PHP can also be embedded into HTML. In this case, both opening tag <?php and closing tag ?> are used.

For example, in the given code, the PHP code has been embedded into the HTML by enclosing it within the <?php and ?> tags.

<html>
<body>
<?php
echo "Hello PHP World!";
?>
</body>
</html>

PHP foreach loop shorthand

In PHP, the shorthand for a foreach loop is:

foreach ($array as $value):
# code block
endforeach;

When embedding in HTML, this is preferable to the bracket syntax, since it is much more clear which code block is being ended with the endforeach.

<ul>
<?php
$array = [0, 1];
foreach ($array as $i):
?>
<li>Duck</li>
<?php
endforeach;
?>
<li>Goose</li>
</ul>

PHP while loop shorthand

In PHP, the shorthand for a while loop is:

while(/*condition*/):
# code block
endwhile;

When embedding in HTML, this is preferable to the bracket syntax, since it is much more clear which code block is being ended with the endwhile.

<ul>
<?php
$i = 0;
while ($i < 2):
?>
<li>Duck</li>
<?php
$i++;
endwhile;
?>
<li>Goose</li>
</ul>

PHP for loop shorthand

In PHP, the shorthand for a for loop is:

for (/*condition*/):
# code block
endfor;

When embedding in HTML, this is preferable to the bracket syntax, since it is much more clear which code block is being ended with the endfor.

<ul>
<?php
for ($i = 0; $i < 2; $i++):
?>
<li>Duck</li>
<?php
endfor;
?>
<li>Goose</li>
</ul>

Learn More on Codecademy