How to Print output in PHP | print () & echo () PHP functions : Tutorial 3

Our tutorial series is straight forward. It contains least theory and more examples for better understanding.

In the last two articles we studied,

Tutorial 1 – Basics of PHP such as syntax

Tutorial 2- Variables and their scope

In this article we are going to see how to display output in PHP. Every programming language has some statement to print the output. In PHP we use the echo or print to show the output.

How to Print output in PHP:

Difference between Print and echo statement:
Echo is most commonly used for displaying the output in PHP. There is a short difference between echo and print.

Echo: Can display output of one or more strings. Print: Can display output of only one string

Echo statement in PHP:

<html>
<?php
echo “<h1>Checking the echo in PHP</h1>”;
echo “HI Guys, how are you doing?<br>”;
echo “Hope”, “everything”,”is fine”;
?>
</html>

The output of following code will be this:

Checking the echo in PHP HI Guys, how are you doing? Hope everything is fine

Displaying content of variables in PHP:

We can display the contents of variables using echo command. Follow the example below for better understanding.

<?php
$var1="Hey Newbies";
$var2="Learning PHP basics";
$sites=array("Google","facebook","Twitter");

echo $var1;
echo "<br>";
echo "are you $var2";
echo “<br>”;
echo "Best search engine is {$sites[0]}";
?> 

Output of following code is as follows:

Hey Newbies are you learning php basics Best search engine is Google

Print Statement in PHP:

Print command can also be used to display output strings in PHP. Follow the example below for better understanding of print command.

<html>
<body>

<?php
print "<h2>Learning PHP on brainytuts.com</h2>";
print "Just finished with echo statement<br>";
print "Now I am about to learn print statement";
?>

</body>
</html>

Output of the following code will be as follows:

Learning PHP on brainytuts.com Just finished with echo statement Now I am about to learn print statement
Displaying Contents of variable using print statement in PHP:

As in echo statement you can also save contents of variable using print command. Check the example below.

<html>
<?php
$var1 = “using print statement”;
print $var1;
?>
</html>

It’s easy to guess output of following code. It will display the statement in $var1.

Most of the people use echo to display the output. It’s a great practice to use echo as it supports multiple strings.

If you have any problems regarding PHP ask them in comments section. If you find this article useful share it with interested people around you.

Leave a Reply