In PHP there are two ways to “print” HTML markup, text, and variables, using print
and echo
. These are essentially interchangeable, though print
is slower, so best practice is to use echo
. “print” has a return value of 1 (so it can be used in expressions), while “echo” does not. print can take one argument, while echo can take multiple arguments.
This code demonstrates how both echo and print work interchangeably. It also shows how to print a mixture of HTML markup, text, and variable data in PHP.
<?php $txt1 = "Using echo"; $txt2 = "writephponline.com"; $x = 89; $y = 10; echo "<h3>" . $txt1 . "</h3>"; echo $txt2 . " is a good place to test PHP code.<br>"; echo "89 x 10 = ". $x * $y; $txt1 = "Using print"; $txt2 = "phptester.net"; $x = 45; $y = 8; print "<h3>" . $txt1 . "</h3>"; print $txt2 . " is a good place to test PHP code.<br>"; print "45 x 8 = ". $x * $y; ?>
Which yields:
Using echo
writephponline.com is a good place to test PHP code.
89 x 10 = 890
Using print
phptester.net is a good place to test PHP code.
45 x 8 = 360
This code demonstrates that echo can output multiple comma separated arguments:
<?php echo "This ", "string ", "was ", "made ", "with multiple parameters."; ?>
which yields:
This string was made with multiple parameters.
However, print does not support multiple arguments. PHP will give an error when it sees a comma as an argument to print. For example:
<?php print "This ", "string ", "was ", "made ", "with multiple parameters."; ?>
yields:
FATAL ERROR syntax error, unexpected ',' on line number 2
For more information about print and echo see:
https://www.w3schools.com/php/php_echo_print.asp
http://php.net/manual/en/function.print.php
http://php.net/manual/en/function.echo.php