Echo and Print Statements
In PHP, there are two basic ways to send output to the browser: echo and print. echo and print are not functions but language constructs in PHP.
The PHP echo Statement
The echo statement can be used with or without parentheses: echo or echo(). It outputs one or more expressions, with no additional newlines or spaces. Echo does not return a value. The output text can contain HTML markup.
Eg:
<?php
$x = 20; $y = 5;
$sum = $x + $y;
echo "<h1>PHP echo statement</h1>";
echo "<br>";
echo $x - $y;
echo "<br>";
echo "Sum of x and y is: ".$sum;
?>
The PHP print Statement
The print statement can be used with or without parentheses: print or print(). Main difference with the echo statement is that print always returns a value 1 (integer). The output text can contain HTML markup.
Eg:
<?php
$x = 20; $y = 5;
$sum = $x + $y;
print "<h1>PHP echo statement</h1>";
print "<br>";
print $x - $y;
print "<br>";
print "Sum of x and y is: ".$sum;
?>
Difference between echo and print
echo | |
---|---|
echo can take more than one parameter when used without parentheses. | print only takes one parameter. |
echo is not a function but a language construct. | print is also a language construct but it behaves like a function because it returns a value 1. |
Theoretically, echo is faster because it does not return any value. | print is slower compared to echo. |
echo can pass multiple string separated by commas ( , ) | In print, we cannot pass multiple arguments. |