PHP – What is the difference between echo and print?

PHP can sometimes be confusing where it shouldn’t be. One area of confusion is the issue with duplicate built-in functions. I’m always inclined to think that developers probably had good reason to make duplicates and the most of the times its good assumption.

But is it always true? Let’s see on the example of echo end print functions.

Both functions are used for printing out strings. If you feed any of the functions with something else than string they will do their best to convert the input to string which is not always a success. For example, printing numbers will probably do what you expected but for arrays, you’ll run into an issue. So keep in mind that it’s better to convert the input to string (if it’s not a string) before you feed it into the function.

Now when we know similarities let’s see the differences. Actually, there are not many:

  • echo is able to handle multiple inputs parameters (which is not something you can’t live without – you can always concatenate inputs before you feed it into the function)
  • print returns value of 1 (also not extremely useful – I have never seen a piece of code that uses this but it doesn’t mean it’s non-existent).

Since print is returning value it’s a bit slower but the results are marginal and almost not worth mentioning. Some people are arguing that print might be useful in ternary operations or in building more complex expressions. However, it always returns 1, no matter if the function is successful or not, so it’s not very useful if you’re asking me.

Moreover, PHP documentation says print and echo are not functions but the language constructs which means PHP interpreter recognize them as integral parts of the language. For functions, even for built-in ones, there is a bit more processing overhead, so we can say constructs are faster.

To answer the question from the beginning, there is no significant difference between print and echo. It’s the thing of personal preference but in so-called expert developers circles, there will always be a debate whether one is better than other.

Leave a Reply

Your email address will not be published. Required fields are marked *