PHP Echo and Print

echo and print are the two language constructs PHP uses to send text and values to the output, such as a web page or the terminal.

Displaying data is one of the first things you do in PHP, and the language offers two closely related tools for it: echo and print. Both write output, and in everyday code they are almost interchangeable, but there are small differences worth knowing. Note that neither is a function; they are language constructs, so the parentheses around their arguments are optional.

Using echo

echo outputs one or more values and returns nothing. It is the most common choice because it is slightly faster and can accept several arguments separated by commas. You can pass strings, numbers, or the results of expressions.

echo with one and several arguments

<?php
echo "Hello, world!";
echo "<br>";
echo "The sum is ", 2 + 3, ".";  // multiple values
?>

Using print

print also sends text to the output, but it accepts only a single argument and always returns the value 1. Because it returns a value, print can be used inside an expression, which echo cannot. In practice this feature is rarely needed.

print returns a value

<?php
print "Welcome!";
print "<br>";
$result = print "This is printed";  // $result becomes 1
echo "<br>" . $result;
?>

Single vs double quotes

How you quote a string changes what gets printed. Double quotes let PHP replace variables and escape sequences such as \n with their values, while single quotes treat the text literally. This applies to both echo and print.

Variable interpolation depends on quote type

<?php
$name = "Sara";
echo "Hello, $name";   // Hello, Sara
echo '<br>';
echo 'Hello, $name';   // Hello, $name
?>
Featureechoprint
Return valueNoneAlways 1
Multiple argumentsYesNo
Usable in expressionsNoYes
Relative speedSlightly fasterSlightly slower
Note: For most output, reach for echo. Choose print only in the rare case where you need a construct that returns a value inside a larger expression.
Note: Because both are language constructs rather than functions, echo "Hi"; and echo("Hi"); behave the same way.

Exercise: PHP Echo and Print

Can print() output several comma-separated values in one call the way echo can?