PHP: Echo vs Print

Sean Wragg
Sep 2, 2008 · 2 min read

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

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

// 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

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.

sean3z

Code, Comics, and Fhqwhgads!

sean3z

Code, Comics, and Fhqwhgads!

Sean Wragg

Written by

Writing about code, comics, and fhqwhgads!

sean3z

Code, Comics, and Fhqwhgads!