PHP Echo and Print Statements

Updated: April 9th, 2022, 09:37:30 IST
Published: April 8th, 2022
PHP Echo and Print Statements
Title: PHP Echo and Print Statements

There are two basic techniques to get output in PHP: echo and print. In this tutorial, we use echo or print statement to display data on the screen. As a result, this topic offers a bit additional information regarding those two output statements.

PHP echo Vs print Statements

The Similarities:

echo and print are almost the same. They are both used to display data to the screen.

The differences:

echo has no return value while print has a return value of 1 so it can be used in expressions.

echo can take multiple parameters (although such usage is rare) while print can take one argument.

echo is marginally faster than print.

PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().

Display Text

The following example shows how to output the result data in the form of text with the echo command (notice that the text can contain HTML markup):


<?php

echo "<h2>I LOVE PHP!</h2>";
echo "<p>Hello world!</p>";
echo "<p>This ", "string ", "has ", "multiple parameters.</p>";

?> 

Output:

Output: echo and print statement display text

Output: echo and print statement display text

Display Variables

The following example shows how to output the result data in the form of text and using variables with the echo statement:


<?php

$var1 = "I LOVE PHP!";
$var2 = "Solvprog.com";
$x = 81;
$y = 9;

echo "<h2>" . $var1 . "</h2>";
echo "<p>Welcome to " . $var2 . "</p>";
echo $x + $y;
?>

Output:

Output: echo and print statement display variables

Output: echo and print statement display variables

PHP print Statement

The print statement can be used with or without parentheses: print or print().

Display Text

The following example shows how to output data with the print command (notice that the text can contain HTML markup):

<?php

print "<h2>I LOVE PHP!</h2>";
print "<p>Hello world!</p>";
print "<p>This string has single parameter.</p>";

?>

Output:

Output: print statement display text

Output: print statement display text

Display Variables

The following example shows how to output data and using variables with the print statement:


<?php

$var1 = "I LOVE PHP!";
$var2 = "Solvprog.com";
$x = 81;
$y = 9;

print "<h2>" . $var1 . "</h2>";
print "<p>Welcome to " . $var2 . "</p>";
print $x + $y;
?>

Output:

Output: echo and print statement display variables

Output: echo and print statement display variables

Echo vs Print in PHP:

How are echo and print different in PHP?

1. Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster than print since it doesn't set a return value if you really want to get down to the nitty gritty.

2. Parameters. print only takes one parameter, while echo can have multiple parameters.