What is the Difference Between PHP echo versus print?

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

There is not a whole lot of difference between the PHP echo versus print construct, but there are a few.   Note that both of them are PHP constructs.  They are not functions.  Hence, the parenthesis are optional.  All of the following works…

echo versus print

echo versus print

Variable interpolation works for both echo and print as long as double-quotes (as opposed to single quotes) are used.

When used without the parenthesis, echo has the advantage that it can take multiple numbers of arguments separated by commas.   It echos them one after another as if it was doing string concatenation.  However, it is not actually doing concatenation because it runs faster than string concatenation.

The following two statements does not work…

wrong echo print statements

wrong echo print statements

This statement …

echo (“Hello “, $name);

does not work because comma separated arguments can not be used when it is using parenthesis.

Print is not able accept multiple arguments regardless of whether it is using parenthesis or not.   Print takes only one argument.

Return Value of echo and print

Usually we don’t care about the return value of echo and print.  We just care what it outputs to the browser.  However, just for academic sake, the echo does not return anything.  So do not do this …

$myResult = echo(“Hello”);  // fails

It will not work.  You get error code 500.

However, print can do it…

$myResult = print(“Hello”);   // ok $myResult is 1

The value that print returns is always “1”.

print behaves more like a function

In that sense, print behaves a little bit more like a function than echo.

For example, print is able to do this …

print like a function

print like a function

whereas echo can not.  However, the workaround for echo is to do this …

echo workaround

echo workaround

Performance Difference between echo and print

As you can see from phpbench.com (run it a few times), there is not much difference in performance between echo and print.  Any difference is slight except when echo is echoing multiple strings separated by commas, in which case its speed is superior to that of dot-concatenation (which is all that print can do).

For this reason alone, I prefer to use echo rather than print.  I think most developers these days prefer echo over print.