PHP echo and print Statements

We frequently use the echo statement to display the output. There are two basic ways to get the output in PHP:

echo and print are language constructs, and they never behave like a function. Therefore, there is no requirement for parentheses. However, both the statements can be used with or without parentheses. We can use these statements to output variables or strings.

Difference between echo and print

echo

print

You can see the difference between echo and print statements with the help of the following programs.

For Example (Check multiple arguments)

You can pass multiple arguments separated by a comma (,) in echo. It will not generate any syntax error.

PHP Example


<?php  
$fname = "Gunjan";  
$lname = "Garg";  
echo "My name is: ".$fname,$lname;  
?>
                   

Output

My Name is GunjanGarg

It will generate a syntax error because of multiple arguments in a print statement.

PHP Example


<?php 
$fname = "Gunjan";  
$lname = "Garg";  
print "My name is: ".$fname,$lname;  
?>
                           

Output

parse error : syntax error, unexpected ',' in D:xampphtdocsp1.php on line 6

For Example (Check Return Value)

echo statement does not return any value. It will generate an error if you try to display its return value.

PHP Example


<?php  
$lang = "PHP";  
$ret = echo $lang." is a web development language.";  
cho "</br>";  
echo "Value return by print statement: ".$ret;   
?>  
                   

Output

parse error : syntax error, unexpected 'echo' (_TECHO)in D:xampphtdocsp1.php on line 4

As we already discussed that print returns a value, which is always 1.

PHP Example


<?php  
$lang = "PHP";  
$ret = print $lang." is a web development language.";  
print "</br>";  
print "Value return by print statement: ".$ret;   
?>       
                   

Output

PHP is web Development language Value return by print statement:1