How to Display PHP Variables in HTML

INTRODUCTION
THE ART OF WEAVING

Welcome to a beginner’s tutorial on how to display PHP variables in HTML. So you have just begun studying the mystic arts of PHP and is wondering how we can put PHP variables into HTML? Well, there are actually a few ways to do that and it can be a little confusing.

Long story short, the easiest way to insert a PHP variable into HTML is to use the <?=$VARIABLE?> short tag. But there are plenty of other means, and just how do we do it?  We shall explore all of that in-depth within this guide, read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

 

PREAMBLE
SOURCE CODE DOWNLOAD

First, here is the download link to the example source code as promised.

 

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SECTION A
THE BASICS

Before we go into deeper into the cyber woods, here are some of the basics and a quick recap on outputting variables. Feel free to skip this section if you are already comfortable.

 

TEXT & VARIABLE OUTPUT IN PHP

1a-output.php
<?php
$hello = "world";
echo $hello; // world
print $hello; // world, returns 1
printf("Foo bar %s", $hello); // Foo bar world

$hello = ["foo", "bar"];
print_r($hello); // Array ( [0] => foo [1] => bar )
var_dump($hello); // array(2) { [0]=> string(3) "foo" [1]=> string(3) "bar" }

Now for the quick recap – There are several ways for us to output a variable or text in PHP:

  • echo – Simply outputs a string.
  • print – This one is kind of baffling. It outputs a string as well, but will return a value of “1”.
  • printf – Outputs a formatted string.
  • print_r – Output nice human-readable information on a given variable.
  • var_dump – Simply dumps whatever is in a given variable (unformatted).

Just what purpose do these serve? We will be using these exact functions to weave variables into HTML in the sections below. So just keep them in mind for the time being.

 

SINGLE & DOUBLE QUOTES

1b-quotes.php
<?php
$hello = "world";
echo '$hello world'; // $hello world
echo "$hello world"; // world world

For this next piece of trivial, some other tutorials may state “you may define strings in both single and double quotes”. Yes, that is true, but there is also a difference between these two.

  • Single quotes will just output whatever you enter inside.
  • If you throw a variable into a double quotes string, it will automatically be concatenated.

So there you go, hope you have learned a new lazy trick with this.

 

 

SECTION B
PHP-HTML WEAVING

Now that we are done with the basics and quick recap, this section will walk you through the art of PHP-HTML weaving.

 

PHP FILE, NOT HTML

If you want to display PHP variables in an HTML page, the very first thing to do is to create a PHP file with HTML code inside.

2a-html.php
<!DOCTYPE html>
<html>
  <head>
    <title>Just HTML Demo</title>
  </head>
  <body>
    <p>This is a PHP file without a single line of PHP code.</p>
    <p>What's more - This is a HTML page!</p>
  </body>
</html>

Yes, this may be confusing to some of you at first – Aren’t we supposed to put HTML code in an HTML file? Well, there are no rules saying that we must… and remember that HTML is essentially just plain text? What we are doing here is exactly outputting text in HTML format with PHP. That’s all.

 

PHP IN HTML

So far so good? Now, remember that pair of <?php and ?> that we normally use in PHP? Those are not for show, and another quick recap.

  • <?php marks the start of the PHP script.
  • ?> marks the end of the PHP script.

With that, we can weave PHP code into the HTML as such:

2b-weave.php
<!DOCTYPE html>
<html>
  <head>
    <title>HTML-PHP Weaving Demo</title>
  </head>
  <body>
    <p>This is a PHP file.</p>
    <!-- PHP START -->
    <?php
    $hello = "FOO BAR!";
    echo "<p>$hello</p>";
    ?>
    <!-- BACK TO HTML -->
    <p>What's more - This is a HTML page!</p>
  </body>
</html>

Take note that there are no limits to how many times we can weave in-and-out of PHP/HTML within a page. For example, we can do some PHP processing at the top, switch to output the HTML, then weave more PHP in the middle of the HTML page – Will go through more of such examples below.

 

 

SHORT TAGS

Now that you have learned the secret of weaving, here is another “lazy goodie” for you – Short tags. Instead of defining full PHP tags and doing echo, we can simply use <?=$VAR?> to weave a variable into the HTML.

2c-short-tag.php
<?php
// WE START WITH PHP
$hello = "world";
$foo = "bar";
// INTO HTML
?>
<!DOCTYPE html>
<html>
  <head>
    <title>HTML-PHP Short Tag Demo</title>
  </head>
  <body>
    <p>This is a <?=$hello?> PHP file.</p>
    <p>What's more - This is a <?=$foo?> HTML page!</p>
  </body>
</html>

 

SECTION C
MORE EXAMPLES

With your new found powers in HTML and PHP, we shall dive into more examples in this section to further hone your ninja coding skills.

 

PHP VARIABLES IN HTML TABLE

3a-html-table.php
<?php
// WE START WITH PHP
$hello = "world";
$foo = "bar";
// INTO HTML
?>
<!DOCTYPE html>
<html>
  <head>
    <title>HTML-PHP Demo</title>
  </head>
  <body>
    <table>
      <tr>
        <td>Hello</td>
        <td><?=$hello?></td>
      </tr>
      <tr>
        <td>Foo</td>
        <td><?=$foo?></td>
      </tr>
    </table>
  </body>
</html>

 

 

PHP VARIABLES IN HTML FORM

3b-html-form.php
<?php
// WE START WITH PHP
$hello = "world";
$foo = "bar";
// INTO HTML
?>
<!DOCTYPE html>
<html>
  <head>
    <title>HTML-PHP Demo</title>
  </head>
  <body>
    <?php if ($_POST) { ?>
      <p>This part will only show after the form is submitted.</p>
      <?php print_r($_POST);
    } ?>
    <form method="post">
      <input type="text" name="hello" value="<?=$hello?>"/>
      <input type="text" name="foo" value="<?=$foo?>"/>
      <input type="submit" value="Submit"/>
    </form>
  </body>
</html>

 

ARRAY & LOOP

3c-html-array.php
<?php
// WE START WITH PHP
$person = [
  "name" => "John Doe",
  "email" => "john@doe.com",
  "gender" => "Male"
];
// INTO HTML
?>
<!DOCTYPE html>
<html>
  <head>
    <title>HTML-PHP Demo</title>
  </head>
  <body>
    <table><?php
      // WE CAN ALSO LOOP AN ARRAY TO QUICKLY CREATE A TABLE
      foreach ($person as $key=>$value) {
        printf("<tr><td>%s</td><td>%s</td></tr>", $key, $value);
      }
    ?></table>
  </body>
</html>

 

HTML TEMPLATE

Yep, just-in-case you have not realized yet – We can put the variables anywhere we want within the page. That includes the head section, where we can use it to create an HTML template system.

3d-top.php
<!DOCTYPE html>
<html>
  <head>
    <title><?=$title?></title>
    <meta name="description" content="<?=$desc?>">
  </head>
  <body>
3d-bottom.php
  </body>
</html>
3d-page.php
<?php
$title = "TEST PAGE";
$desc = "This is a description";
require "3d-top.php";
?>
<p>Hello world!</p>
<p>Foo bar is great!</p>
<?php
require "3d-bottom.php";
?>

 

 

EXTRA
SUMMARY & MORE

That’s all for the code, and here is a small summary that may be useful to you.

 

THE SUMMARY

  • The basic PHP output functions are – echoprintprintfprint_r, and var_dump.
  • Single quote strings will just output whatever you put in.
  • Double quote strings will automatically concatenate variables that you put in.
  • We use a pair of <?php and ?> tags to weave in-and-out of PHP.
  • We can use short tags <?=$VAR?> to quickly echo a PHP variable.
  • PHP variables can really be “weaved” into any part of the HTML.
  • It is a good idea to use loops to run through an array to create an HTML table or list.

 

CHEAT SHEET

How to Display PHP Variables in HTML (Click to Enlarge)

 

DO NOT MIX PHP AND HTML!

So says some of the programming trolls, and don’t listen to them. Here is the million-dollar question – Would you rather use a single for loop or copy-paste the same piece of code a hundred times? I think a more proper way to put the PHP-HTML marriage situation is – Use PHP and HTML together, but don’t keep the library functions and HTML in a single script.

You need to learn how to better organize your scripts, and the model-view-controller (MVC) concept is one of those. Do follow up on my other guide if you are interested:

4 Steps Simple PHP MVC Example (What the Heck is MVC!?)

 

LINKS & REFERENCES

 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *