PHP Printing Constructs

Every programming language offers functions or statements to display messages or results to user. In PHP Printing Constructs are used to display text strings in browser window. These are:

echo

echo can used as a function by passing strings in parenthesis or as a PHP printing construct by giving the string message or variable names without parentheses. echo accepts multiple variables or strings separated by commas.

Syntax

echo  string1, string2, string3….;

OR

echo variable1, variable2,variable3….;

OR

echo  (string1, string2, string3….);

OR

echo  (variable1, variable2,variable3….);

echo construct or function prints string on the screen and does not return anything.

<?php
echo "<h1>Verstality is the middle name of PHP!</h1>";
echo "Hello programmers! Welcome to PHP World<br>";
echo "What you are going to learn is going to be so much fun!<br>";
echo "I ", "Know ", "This ", "Looks ", "Weird ", " But I can print like this in PHP<BR>";
$str1="A ";
$str2="lot ";
$str3="more ";
$str4="to come";
echo $str1,$str2, $str3, $str4;
?>

Output is:

You can see in the code that the arguments passed to echo  are separated by commas.

PHP echo example

print

Like echo print can also be used to print strings but it accepts only one string or one variable in parenthesis or as a PHP printing construct without parentheses. Print always returns 1 and prints a string.

Syntax

print ( string)

OR

print( variable)

Examples

echo “You want to print this”

echo(“you want to print this as well”)

echo prints all the arguments separated by comma either with parentheses or without it.  print accepts only one string argument either with or without parentheses. Print also returns a value to indicate whether the print was successful or not

<?php
print "<h1>Verstality is the middle name of PHP!</h1>";
print "Hello programmers! Welcome to PHP World<br>";
print( "What you are going to learn is going to be so much fun!<br>");
print "I ". "Know ". "This ". "Looks ". "Weird ". " But I can print like this in PHP<BR>";
$str1="A ";
$str2="lot ";
$str3="more ";
$str4="to come";
echo $str1.$str2. $str3. $str4;
?>

Output is:

You can see in the code that the argument passed to print is one concatenated string

PHP print example

Comparing echo and print

echo

print

echo can be used as printing construct as well as a function (echo()) print can be used as printing construct as well as a function (print())
echo accepts any number of string arguments separated by commas print accepts only one string as argument. If you need to print more than one string with one print function, concatenate them with . (dot string operator)
echo does not return anything print always return 1