PHP: Echo vs Print

The following is derived from my post on the (now defunct) hawkee.com forums.

This is a hot topic for those just getting into php. Understanding the difference between print() and echo can be challenging for those unfamiliar with the language.

In my opinion, it really depends what your trying to accomplish that will determine which you should use. Some things to consider:

  1. echo is marginally faster than print()
  2. print() is a function, which can be used in more complex operations.
  3. echo can handle multiple parameters.

echo is faster

As stated, echo is marginally faster than print(). If you’re wondering how much faster, take a look at this.

I’ve created two php snippets: echo.php and print.php

// file: echo.php
for ( $i = 0; $i <= 10; $i++ ) {
echo 'Test';
}
// file: print.php
for ( $i = 0; $i <= 10; $i++ ) {
print('Test');
}

Then I made a snippet to time them both: test.php.

// file: test.php
$t1 = microtime(true);
system('php echo.php');
$t2 = microtime(true);
$r = $t2 - $t1;
echo 'echo: '. $r;

$t1 = microtime(true);
system('php print.php');
$t2 = microtime(true);
$r = $t2 - $t1;
echo 'print: '. $r;

We execute our test.php and see our results.

echo: 0.057446947097778 
print: 0.072533121109009

So ultimately, we confirm that echo is only slightly faster than print().

print() is a function

However, this doesn’t necessarily mean that echo is better than print(), because print() can do something that echo can’t - it can be placed in more complex operations since it's a function.

// ternary operator
($i) ? print('true') : print('false');

Within the above, if the variable $i is set this snippet will print true. Since print() is a function, it’s able to be used within this operation, where echo can not. In fact if you were to attempt to use echo within this statement, php will error in:

Parse error: syntax error, unexpected T_ECHO in test.php on line 2.

echo accepts multiple parameters

Finally, echo can handle multiple parameters but, I think that pretty much speaks for itself. Give the following a try:

echo 'this', 'is', 'really', 'neat!';

So, as stated, it really just depends on what your trying to accomplish. Others may have a different opinion but this is mine and I’m entitled to it :P


Originally published at seanwragg.com on September 2, 2008.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.