This tutorial describes print and echo in PHP. It explains the difference between them and how to use them when coding.
What Is Print in PHP?
Print in PHP creates a statement to print the data as output. It takes single data (a variable or a string) and prints it. It is a language construct and keyword in PHP, not a function. Therefore, developers can use 'print' without using parentheses to create a print statement.
How to Display Strings Using Print?
To print strings, you can write a print statement with the following expressions:
<?php print "This string is displayed using PHP print." ?>
How to Display Variables Using Print?
To print a variable, You can write the print statement with the following expressions:
<?php $txt = "This string is displayed using PHP print."; print $txt; ?>
What Is Echo in PHP?
Echo is used to display the output of the passed parameter. It can print (variables and strings) separated by commas. It is a language construct and keyword in PHP, not a function. Therefore, developers can use 'echo' without using parentheses.
How to Display Strings Using Echo?
To print strings, you can write an echo statement like this:
<?php echo "Echo statement in PHP." ; ?>
How to Display Strings as Multiple Arguments Using Echo?
To pass multiple string arguments using the echo statement instead of a single string argument, users can separate them by a comma (,) operator. For example, if users have multiple strings, namely "Let," "us," and "PHP," then we can use the echo using commas and display them as ("Let," "us," "PHP").
<?php echo "Let," "us," "PHP" ; echo " Here ", "we ", "made ", "a ", "string", "with multiple parameters." ; ?>
How to Print Variables Using Echo?
Printing variables in an echo statement is similar to printing strings.
<?php $txt = "This string is displayed using PHP echo."; echo $txt; ?>
Differences and Similarities Between Print and Echo
|The print statement prints an output. It can be used as an alternative to echo.||The echo statement prints an output.|
|The print statement can be written with or without parentheses.||The echo statement can be written with or without parentheses, just like print.|
|The print statement can accept only one argument at a time; Thus, it can print only a single string.||The echo statement accepts a list of arguments.|
|The print statement always returns a value of 1.||The echo statement returns no value or returns void.|
|The print statement executes slower than the echo statement.||The echo executes comparatively faster than print statement.|