In PHP, we have two ways to get output: we either use the keyword “echo” or “print”.
These two are technically not functions, so you can use them without brackets.
There isn’t really any real difference between what they do. They are both used to display data on a screen.
Displaying Strings, Variables With Echo
EXAMPLE CODE
<?php
Echo "I am line one";
Echo "I am line two";
Echo "I am line three";
Echo "I am line four";
?>
EXAMPLE OUTPUT
Now the reason we add a “
” tag at the end of each line is that by default PHP will not separate lines automatically. Without the break tags, your code will instead display the following.
The difference as you can see is that without the break tags, the lines stick together.
EXAMPLE CODE
<?php
$a = "I am sentence one";
$b = "I am sentence two";
$c = "I am sentence three";
echo $a;
echo "<br>";
echo $b;
echo "<br>";
echo $c;
?>
EXAMPLE OUTPUT
You can display variables using echo without any quotations around them.
PHP Echo And HTML elements
We can display strings, numbers as well as variables using the echo function. However, just displaying plain text is quite boring.
To make our code look more appealing when displayed, we almost always want to embed some HTML tags in our commands. Here, we have attached a “divider” element to some text.
Example
<?php
Echo "<div>I am the first sentence</div>";
Echo "<div>I am the second sentence</div>";
Echo "<div>I am the third sentence</div>";
Echo "<div>I am the fourth sentence</div>";
?>
Output
PHP Echo With A Variable
To display variables inside of HTML tags, you can add them like regular text.
EXAMPLE
<?php
$h1 = "h1";
$h2 = "h2";
$h3 = "h3";
$h4 = "h4";
$h5 = "h5";
Echo "<h1>I am header1 $h1 </h1>";
Echo "<h2>I am header2 $h2</h2>";
Echo "<h3>I am header3 $h3 </h3>";
Echo "<h4>I am header4 $h4 </h4>";
Echo "<h5>I am header5 ”.$h5. “</h5>";
?>
Output
I used two different syntaxes in our example above; both of them are acceptable.
Adding HTML Attributes
Yet even our examples above are quite boring.
To make our website even more interesting, we want to add some descriptions to our HTML.
To add attributes, we write them as we normally do inside of each element.
The main difference is inside of using double quotes, we use single quotes instead.
Example
<html>
<head><title></title></Head>
<style>
.red
{
border: 2px solid red;
}
</style>
<body>
<?php
Echo "<div class='red'>I am the first sentence</div>";
Echo "<div class='red'>I am the second sentence</div>";
Echo "<div class='red'>I am the third sentence</div>";
Echo "<div class='red'>I am the fourth sentence</div>";
?>
</body>
</html>
Output
Here is how we would display an unordered list using PHP.
Example
<?php
echo "<ul>";
$a = "I am a variable";
echo "<li> This is the first list item</li>";
echo "<li> This is the second list item</li>";
echo "<li> This is the third list item </li>";
echo "<li> This is a variable $a </li>";
echo "</ul>”;
?>
Output