Deep Tech Point
first stop in your tech adventure

Difference between echo and print in PHP

January 2, 2021 | PHP

PHP can sometimes be confusing when it shouldn’t be. One area of confusion is the issue with “duplicate” built-in functions. I’m always inclined to think that language makers probably had a good reason to make duplicates and most of the time that is a good assumption.
But is it always true? Let’s see an example of echo end print functions. Technically speaking neither echo nor print are functions but language constructs so you don’t need to use parentheses with its arguments.

<?php
echo "get ready: ", 1, 2, 3, " go";  // outputs get ready: 123 go
print "get ready: 123 go";  // print can't handle multiple arguments like echo
?>


Both functions output a string. However, there is a difference. Echo can output one or more strings and print always returns the value of 1. If you pass to these functions any other type of argument and not a string, they will do their best to convert the input to a string, and that 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 a string (if it’s not a string) before you pass it into a function.

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

Since print is returning a value, it’s a bit slower but the results are marginal and almost not worth mentioning. If you look at the internal source code, both functions are invoking the same handler. The only difference is that print returns the value of 1, so it allocates a temporary variable for that, which means it’s a bit slower. Some people are arguing that print might be useful in ternary operations or in building more complex expressions.

For example, you can do something like this:

$test? print "pass": print "error"

Moreover, PHP documentation says print and echo are not functions but language constructs which means PHP interpreter recognizes 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 a thing of personal preference but in so-called expert developers circles, there will always be a debate about whether one is better than the other for some special cases. If you really need to decide upfront then choose echo.