Echo and Print are almost similar with both being not a function but language constructs, and both are used to output a string or data to the screen. But despite their similarity, they actually have some differences though quite subtle.
So, what are the differences? And perhaps, an even more interesting question would be, which is better between echo vs print?
These are probably one of the most common questions that will come out in a job interview.
Echo vs Print
1. Echo is marginally faster. Speed-wise, echo is faster because it doesn't set a return value.
2. Print behaves like a function and can be used in expressions. Print can be used as part of a more complex expression where echo cannot. ie. $real ? print "true" : print "false"; If Print is used in a variable, it returns a value of 1 as in the case of $return = print "Hello World". Echo can't do this. Print is also part of the precedence table which it needs to be if it is to be used within a complex expression. It is just about at the bottom of the precedence list though. Only ,
, AND
, OR
, and XOR
are lower.
3. Echo can take multiple parameters, separated by commas. Echo can take and concatenate multiple parameters, for example: echo 'Welcome ','to ','New York'; On the other hand, Print can only take one parameter.
Additional Notes
While echo and print can be both used to output data, it is worth noting that echo is faster, making it more preferable to use if you are just outputting a string. But it depends on usage, there are instances such as you wanted to print only when a variable has content, such as in the case of:
$str = 'String has texts';
$str ? print "String has content" : "";
Output:
String has content
In this case, print is more preferable as you don't have to create an if condition.
It is also worth noting that since echo and print are language constructs, they actually don't need strings to be encased in a parenthesis, though encasing strings are still valid.
Example:
echo("hello world");
print("hello world");
Both will still output "Hello World".
However, you can't echo strings separated by comma inside a parenthesis like in echo("Hello","World"); though you can echo("Hello"),("World"); Print will never work in both examples.