PHP Tidbit: echo vs print
Posted by Jon Lee in Web Development, tags: echo, PHP, print, tidbit, tips, web developmentAfter talking to a few web developers and reading through a lot of other people’s code, I have come to the conclusion that most people use the “echo” command to output text. What is interesting, is that many tutorials and beginner resources in fact teach the “print” command to accomplish task.
On the surface, echo and print seems to accomplish the same thing, but they have a couple of subtle differences.
Print returns a boolean
When you call the print function, it returns either true or false based on whether or not it executed properly. Therefore, you can do something like this with print but not with echo:
if ( !print(“hello!”) ) {
die(“print failed”);
}
Echo is Faster
Since echo does not return a boolean value, it is naturally faster as empirical tests have demonstrated. However, the difference is so small that when it comes to actual use, it is pretty much negligible.
So Which to Use?
Honestly, it doesn’t matter. But keeping in the spirit of efficiency, echo should be used all the time unless you require the boolean return value of print. I’m having difficulty coming up with a situation where a boolean return value would be useful in an output function. If anyone has a good example, I would love to hear it!
P.S. Echo is also easier to type as there are less letters and less transitions between hands.
Popularity: 2% [?]
Entries (RSS)