PHP echo and print Statements

The echo and print statement displays the output of the variable’s values to the browser. The echo statement is a language construct and does not return a value. Therefore, it is unnecessary to use it as a function, and no parentheses are needed. You can use echo to print multiple strings values separated by a comma. 

Displaying Simple String

A simple string value can be displayed using the echo statement. The string is passed as an argument within double quotes or single quotes.

The following example shows the text Hello World.

			

<?php
echo "Hello World!";
?>

				

Output:

Hello World!

Displaying Multiple Strings

Multiple strings are printed by passing them as arguments separated by comma(,). Suppose you want to print the Hello and World texts, use the following echo statement.

			

<?php
echo " Hello "," World";
?>

				

Output:

Hello World

Displaying HTML Code

HTML code is displayed in the same manner as we display string. You can include HTML code within the string. Consider the following example to show HTML Code.

			

<?php
echo ‘<h1 style="color:grey">Heading Text.</h1>’;
echo ‘<p style=”color: red;”>Ths is parapraph text.</p>’;
?>

				

Output:

<h1 style="color:grey">Heading Text.</h1> <p style=”color: red;”>Ths is parapraph text.</p>

Displaying variables

Consider the following example to print the value of variables. The tag is appended to the variables using the concatenation operator to insert a new line.

			


<?php
$var1 = "Hello World!";
$var2 = 123;
$var3 = array("Mercury", "Venus", "Earth");

echo $var1 . "<br>";
echo $var2 . "<br>";
echo $var3[0] . "<br>";

?>


				

Output:

Hello World 123 Mercury

Print Statement

The print statement is similar to the echo statement with a few differences. It takes only a single argument, and it returns a value of 1. Most developers prefer echo statement as it is slightly faster than print statement.

To display a simple string.

			

<?php
print "Hello World!";
?>

				

Output:

Hello World!

To display the HTML Code.

			

<?php
print ‘<h1 style="color:grey">Heading Text.</h1>’;
print ‘<p style=”color: red;”>Ths is parapraph text.</p>’;
?>

				

Output:

<h1 style="color:grey">Heading Text.</h1> <p style=”color: red;”>Ths is parapraph text.</p>

To display variables.

			

<?php
$var1 = "Hello World!";
$var2 = 123;
$var3 = array("Mercury", "Venus", "Earth");

print $var1 . "<br>";
print $var2 . "<br>";
print $var3[0] . "<br>";

?>

				

Output:

Hello World 123 Mercury