PHP echo and print Statements
PHP gives you two basic statements for producing output, echo and print, and they are nearly interchangeable. The differences are small. print returns a value of 1, which means you can use it inside an expression, while echo returns nothing. echo accepts several parameters (something you'll rarely see in practice), but print takes just one argument. echo also runs slightly faster.
The PHP echo Statement
Use echo to output one or more strings. Parentheses are optional, so both echo and echo() are correct.
Display text with echo
Output some text with echo. The strings can include HTML markup, as the heading and line break show here:
Output: PHP script
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!";
?>
Display variables with echo
Besides plain text, echo can print the contents of variables, here a string, an integer and a decimal number:
Output: PHP script
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
Display variables in a string with echo
Inside a double-quoted string, a variable is replaced by its value, so echo prints the text with $txt filled in:
Output: PHP script
<?php
$txt = "PromptCookbook";
echo "I love $txt!";
?>
The PHP print Statement
Use print to output a string; it gives back 1 every time. As with echo, parentheses are optional, so you can write print or print().
Display text with print
The same text output, now written with print. Again, the strings can carry HTML markup:
Output: PHP script
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Display variables with print
print handles variables just as well. Each value here goes out in its own statement:
Output: PHP script
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
print $txt;
print "<br>";
print $x;
print "<br>";
print $y;
?>
Display variables in a string with print
Double-quoted strings work the same way with print, so $txt is swapped for its value:
Output: PHP script
<?php
$txt = "PromptCookbook";
print "I love $txt!";
?>