By now, if you are working with PHP, I'm sure that you encountered using echo and print. But do you know the differences between them and are there any differences between them? In this article we will take a look at echo and print, compare them and explain its features.

Table of Contents

In PHP, there are two ways to display output: echo and print. These are not functions, but language constructs. There are minor differences between echo and print, but first lets start with echo.

Echo

The echo statement is a language construct that can be used to output one or more strings. It's arguments can be string, numbers, variables values and etc. Echo doesn't return any value. When used with multiple strings, they need to be split by comma (,). The echo statement can be used with or without any parenthesis, but if used with parenthesis, the parenthesis are part of the expression, not a part of the echo syntax itself. Echo doesn't add newlines or whitespaces. In the code block below are showcased different examples of using echo. Also at the end of each statement is added a newline character for formatting purposes.

<?php
echo "This string is printed by using echo! \n";

$string = "Hello World";
echo "Display ", "value ", "from ", "variable: ", $string, "\n";

echo "Display numbers: ", 62432, "\n";
echo("Displaying string using parenthesis. \n");
echo("hello"), (" world! \n");

If the code block is executed in a terminal, it will produce results as these:

This string is printed by using echo! 
Display value from variable: Hello World
Display numbers: 62432
Displaying string using parenthesis. 
hello world!

Print

The print statement, as the echo statement, is also a language construct, but unlike echo, it accepts only one argument and it always returns 1.

In the code block below, we are using print statements to write the same output as we did with echo.

print "This string is printed by using print! \n";

$string = "Hello World";
print "Display " . "value " . "from " . "variable: ". $string . "\n";
print "Display numbers: ". 62432 . "\n";
print "Displaying string using parenthesis. \n";
print "hello world! \n";

Conclusion

There two major differences between echo and print. Echo accepts multiple arguments and returns no value, on the other hand print accepts only one value and returns a value of 1. Which one is used will depend on the situation that you encounter. If you want to dive deeper, you can checkout the official PHP documentation for echo and print.

Source code is available on my Github.


php