In this beginner-friendly tutorial, you will learn various ways you can print PHP variables in HTML.
Method 1 – PHP Delimiters
The first method is to use PHP delimiters. We know that PHP will only process the code between the <?php and ?> tags. The other part is ignored or printed by the PHP processor.
To print a variable in PHP using delimiters, we can use the PHP opening and closing tags and insert the variables.
For example, the following code shows how to use PHP delimiters to print a variable.
<?php
$var = 10;
?>
<!-- print variable -->
<p><?php echo $var; ?></p>
The above code will take the variable defined and substitute it inside the delimiters.
Method 2 – PHP Short Tags
It gets annoying and cumbersome to switch between PHP and HTML tags to process PHP information. We can try to overcome this by using a short-form of the method as:
The syntax is as:
For example, we can print PHP variable using the short-form as:
<?php
$var = 10;
?>
<!-- print variable -->
<p><?=$var?></p>
Similar to the previous example, PHP will inject the variable’s value into the HTML.
Method 3 – Using ECHO HTML Tags
The other method, most infuriating of all, is to echo HTML information. You use the PHP echo method to print the HTML content.
The example below shows how to use the echo method to print variables into HTML.
<?php
$var = 10;
echo "<p>This is a variable $var</p>";
?>
Once PHP sees the <?php and ?> tags, it will process the information including the echo method. The variable’s value will be substituted for the variable in the HTML tag. The same case can be applied to other PHP print methods, such as print and print_r.
This method can become hard to read, especially in a code with many variables and HTML content.
Method 4 – Format Print
PHP also provides the printf method. Although it may seem useless at first, it allows you to format an output string.
The following example shows how to use the printf method to print a variable.
<?php
$var = 10;
printf("<p><b>%s:</b></p>", $var);
?>
Feel free to check the documentation to learn more about the printf method.
Closing
This guide shows you how you can add PHP information inside HTML markup. This is very handy when building dynamic web applications with PHP.