Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Sep 24 Previous

Item 547235

What is the difference between echo and print?

A: echo is an language construct and print is a function.
B: print can be used in complex expressions.
C: print buffers the output and echo doesn't, that's why echo is faster.
D: The are aliases, there are no differences.

Answer

Both echo and print are language constructs. In my opinion there are two main differences, look at the following code:

<?php

echo "Yoda";
print "Yoda";

echo("says");
print("says");

echo ":", "do", "or";
//print ":", "do", "or";

//echo("don't", "there", "is");
//print("don't", "there", "is");

//$b = true ? echo("no") : echo("also");
$b = true ? print("no") : print("also");

//var_dump(echo("trying"));
var_dump(print("trying"));

?>

Line 3 and 4 show that print and echo are language constructs: they are using arguments without brackets.

Line 6 and 7 show that brackets are (obviously) allowed too.

Line 9 and 10 show a freaky usage of multiple arguments that only can be used with echo.

Using brackets is not going the help print here but echo neither as shown in line 12 and 13. Note that if print was a function no syntax error would have occurred and at least "don't" should have been printed out.

In line 15, 16, 18 and 19 echo are print are used as expression in a more complex one. An expression in PHP is anything that has a value and print returns always the value 1. echo returns nothing so you can't use it in another expression.

So the differences are:

  1. You can use multiple arguments using echo.
  2. print is an expression and therefore can be used in more complex ones.

That caching stuff is just nonsense I made up: imagine echo statements at the end of your code being printed before print statements placed at the top of your script. That leaves B as the correct answer.

Also on forums there's some debate on the usage of print. Some state you should not use it because it would be slower. I suppose that's right but I don't think the difference will be significant and therefore not important. Replacing print with echo is not going to make any difference if your application is not responsive.