PHP Echo / Print
echo and print are the two basic ways to send output from PHP. In a web request, that output becomes the HTTP response body — usually the HTML the browser displays. In the command line, it appears in the terminal.
Both look and behave similarly, but they have small, important differences. This lesson explains how each works, how they differ, and how to avoid common output mistakes.
What echo and print Are
Neither echo nor print is a function. Both are language constructs — keywords built into the PHP language itself, like if or return.
Why This Matters
- Parentheses are optional.
echo "Hi";andecho("Hi");both work, because the parentheses are simply grouping the expression, not marking a function call. - They cannot be used where a function is required. For example, you cannot pass
echoas a callback toarray_map()or call it through a variable ($fn = 'echo'; $fn('Hi');fails). - They have their own parsing rules, which explain several surprising behaviors covered below.
The echo Statement
Syntax
echo expression;
echo expression1, expression2, ...;
Example
<?php
$course = "PHP Basics";
$lessons = 24;
echo "Welcome to $course!\n";
echo "This course has ", $lessons, " lessons.\n";
echo 'Enroll today.', "\n";
Output
Welcome to PHP Basics!
This course has 24 lessons.
Enroll today.
How It Works
- The first
echooutputs a double-quoted string.$courseis replaced with its value and\nadds a line break. - The second
echoreceives three arguments separated by commas. Each one is output in order, with nothing added between them. - The third mixes a single-quoted string and a double-quoted newline. Single quotes print text literally, so
\nmust be in double quotes to produce a line break.
echo outputs exactly what you give it. It does not add spaces between arguments or a line break at the end.
Output in a Web Page
When PHP runs in a browser, \n produces a line break in the HTML source, but browsers render line breaks as spaces. Use HTML for visible structure:
<?php
$course = "PHP Basics";
echo "<h2>$course</h2>";
echo "<p>Start with variables and data types.</p>";
Output (rendered in the browser)
PHP Basics (as a heading)
Start with variables and data types.
The print Statement
Syntax
print expression;
Example
<?php
$user = "Nisha";
print "Hello, $user!\n";
print("Your session is active.\n");
Output
Hello, Nisha!
Your session is active.
print produces output exactly like echo with a single argument.
Differences Between echo and print
| Feature | echo | print |
|---|---|---|
| Number of arguments | One or more, separated by commas | Exactly one |
| Return value | None — it is a statement | Always returns 1 |
| Can be used inside an expression | No | Yes |
| Speed | Marginally faster (no return value) | Marginally slower — the difference is irrelevant in practice |
| Common usage | The standard choice in almost all code | Rare; seen in older code and specific expression contexts |
echo Accepts Multiple Arguments; print Does Not
<?php
echo "A", "B", "C"; // valid
print "A", "B", "C"; // Parse error
print Returns a Value
Because print always returns 1, it can appear inside expressions:
<?php
$isDebug = true;
$isDebug && print "Debug mode is on\n";
$result = print "Printing...\n";
echo "print returned: $result\n";
Output
Debug mode is on
Printing...
print returned: 1
- In
$isDebug && print "...", theprintruns only when$isDebugis true, because&&stops evaluating as soon as the left side is false ("short-circuit" evaluation). $resultreceives the return value ofprint, which is1.
echo cannot do this — $x = echo "Hi"; is a parse error.
This expression usage is uncommon. In readable code, an if statement is clearer than $isDebug && print .... The practical conclusion: use echo by default.
Comma vs Concatenation in echo
There are two ways to output several values with echo:
<?php
$name = "Vikram";
$points = 340;
echo "Player: ", $name, " | Points: ", $points, "\n"; // commas
echo "Player: " . $name . " | Points: " . $points . "\n"; // dots
Output
Player: Vikram | Points: 340
Player: Vikram | Points: 340
What Is the Difference?
- Commas pass separate arguments to
echo. Each one is output individually. No combined string is created. - Dots are the concatenation operator. PHP first builds one complete string from all the parts, then
echooutputs that single string.
The results look identical. Commas avoid building an intermediate string, but the performance difference is negligible. Choose the style that reads best. Concatenation has one advantage: the combined expression can also be stored in a variable or returned from a function, so it is more flexible when code is refactored.
Operator Precedence With Concatenation
Mixing . with arithmetic requires care:
<?php
$price = 100;
$tax = 18;
echo "Total: " . $price + $tax . "\n";
Output (PHP 8.0 and newer)
Total: 118
Since PHP 8.0, + and - have higher precedence than ., so the addition happens first. In PHP 7, the same code evaluated left to right — "Total: 100" + 18 — producing a warning and a wrong result.
Using commas or parentheses removes any doubt and works in every version:
echo "Total: ", $price + $tax, "\n";
echo "Total: " . ($price + $tax) . "\n";
The print Precedence Trap
Because print is not a function, parentheses do not limit its argument. This leads to a classic surprise:
<?php
print("Hello") && print("World");
Output
World1
Why This Happens
PHP reads this as:
print (("Hello") && print("World"));
- The argument of the first
printis the entire expression("Hello") && print("World"). - To evaluate
&&, PHP evaluates"Hello"(truthy) and thenprint("World"), which outputsWorldand returns1. "Hello" && 1evaluates totrue.- The first
printoutputstrue, which is converted to the string"1".
The text Hello is never printed. The parentheses around "Hello" only group that one value; they do not end the print statement. The same principle applies to echo("a") . "b" — the . is part of the expression passed to echo.
Lesson: do not write echo or print as if they were function calls inside larger expressions.
How Different Types Are Output
echo and print convert every value to a string before output. The conversion rules can be surprising:
Example
<?php
echo "Integer: ", 42, "\n";
echo "Float: ", 3.50, "\n";
echo "True: ", true, "\n";
echo "False: ", false, "\n";
echo "Null: ", null, "\n";
Output
Integer: 42
Float: 3.5
True: 1
False:
Null:
| Value | Output as String |
|---|---|
Integer 42 | 42 |
Float 3.50 | 3.5 (no trailing zeros) |
true | 1 |
false | empty string |
null | empty string |
Because false and null print as nothing, echo is not suitable for inspecting values while debugging. Use var_dump(), which shows the type and value:
<?php
var_dump(false);
var_dump(null);
var_dump(3.50);
Output
bool(false)
NULL
float(3.5)
To display a float with a fixed number of decimal places, such as a price, use number_format() or printf() (see PHP printf / sprintf).
Arrays Cannot Be Echoed
<?php
$colors = ["red", "green", "blue"];
echo $colors;
Output
PHP Warning: Array to string conversion in /path/script.php on line 3
Array
PHP cannot convert an array into a meaningful string, so it prints the word Array and raises a warning. To output array contents, choose a method:
<?php
$colors = ["red", "green", "blue"];
echo implode(", ", $colors) . "\n"; // join elements into one string
print_r($colors); // human-readable structure (debugging)
Output
red, green, blue
Array
(
[0] => red
[1] => green
[2] => blue
)
Objects Need __toString()
<?php
$date = new DateTime();
echo $date;
Output
PHP Fatal error: Uncaught Error: Object of class DateTime could not be converted to string
An object can only be echoed if its class defines a __toString() method. For DateTime, use echo $date->format('Y-m-d');. The __toString() method is covered in Magic Methods.
Outputting Multiline Text
Long Strings
<?php
echo "Line one
Line two
Line three\n";
A string literal can span several lines; the line breaks are part of the string.
Heredoc for Larger Blocks
For larger blocks of text with variables, heredoc syntax avoids quote-escaping problems:
<?php
$name = "Deepa";
$plan = "Pro";
$renewal = "15 November 2026";
echo <<<TEXT
Hello $name,
Your $plan plan renews on $renewal.
Reply to this email if you have questions.
TEXT;
Output
Hello Deepa,
Your Pro plan renews on 15 November 2026.
Reply to this email if you have questions.
Heredoc behaves like a double-quoted string, so variables are interpolated and " characters need no escaping. It is covered fully in Heredoc and Nowdoc.
The Short Echo Tag
In HTML templates, <?= ... ?> is shorthand for <?php echo ... ?>:
<?php $title = "Pricing"; ?>
<h1><?= $title ?></h1>
Output
<h1>Pricing</h1>
The short echo tag also accepts comma-separated values (<?= $first, ' ', $last ?>), because it is equivalent to echo. It is always available in modern PHP. See PHP Tags for details.
Practical Example: A Formatted Order Confirmation
<?php
$orderId = 50213;
$customer = "Rahul Mehta";
$items = ["Bluetooth Speaker", "USB-C Cable", "Phone Stand"];
$total = 3497.5;
$isExpress = true;
echo "<h2>Order #", $orderId, " confirmed</h2>\n";
echo "<p>Thank you, ", htmlspecialchars($customer), ".</p>\n";
echo "<ul>\n";
foreach ($items as $item) {
echo " <li>", htmlspecialchars($item), "</li>\n";
}
echo "</ul>\n";
echo "<p>Total: ₹", number_format($total, 2), "</p>\n";
if ($isExpress) {
echo "<p><strong>Express delivery selected.</strong></p>\n";
}
Output (HTML)
<h2>Order #50213 confirmed</h2>
<p>Thank you, Rahul Mehta.</p>
<ul>
<li>Bluetooth Speaker</li>
<li>USB-C Cable</li>
<li>Phone Stand</li>
</ul>
<p>Total: ₹3,497.50</p>
<p><strong>Express delivery selected.</strong></p>
Step-by-Step Explanation
- Comma-separated
echoarguments combine fixed HTML with dynamic values without building intermediate strings. htmlspecialchars()escapes customer and product names, so characters like<or&in the data cannot break the HTML or inject scripts.- A
foreachloop outputs one<li>per item. number_format($total, 2)produces3,497.50— two decimal places with a thousands separator — instead of PHP's default3497.5.- The
\ncharacters keep the generated HTML source readable; they do not affect how the page looks.
For larger HTML blocks, leaving PHP mode and using <?= ?> is usually more readable than many echo statements. See PHP and HTML.
Where Output Goes
echo and print write to PHP's output stream:
- In a web request, output is sent to the browser as the response body. Once any output is sent, HTTP headers can no longer be changed, which is why
header()andsetcookie()must be called before anyecho. - In the command line, output goes to standard output (the terminal), where it can be redirected to a file:
php report.php > report.txt. - With output buffering enabled, output is collected in memory first and can be modified or discarded before sending. This is covered in Output Buffering.
Common Mistakes
Echoing Arrays or Objects
Effect: Array to string conversion warning, or a fatal error for objects.
Fix: Use implode(), a loop, print_r(), var_dump(), or json_encode() for arrays; call a formatting method for objects.
Using echo to Debug Booleans and Null
Effect: false and null print nothing, so you cannot tell them apart from an empty string.
Fix: Use var_dump() while debugging.
Expecting print to Accept Multiple Arguments
Effect: Parse error.
Fix: Use echo with commas, or concatenate into one string for print.
Writing echo as a Function Inside Expressions
Effect: Unexpected output, such as World1 instead of HelloWorld.
Fix: Use echo and print as standalone statements.
Outputting Before Headers
Effect: Cannot modify header information - headers already sent.
Fix: Call header(), setcookie(), and session_start() before any echo, print, or HTML output.
Echoing Unescaped User Data
Effect: Broken markup and cross-site scripting (XSS) vulnerabilities.
Fix: Wrap external values in htmlspecialchars() when outputting HTML.
Best Practices
- Use
echoas the default output statement; reserveprintfor the rare cases where a return value is needed. - Write
echowithout parentheses to make it clear it is not a function. - Use commas or parentheses when mixing concatenation and arithmetic.
- Use
var_dump()— notecho— to inspect values while debugging. - Escape all external data in HTML output.
- For formatted numbers, use
number_format()orprintf().
Official reference: https://www.php.net/manual/en/function.echo.php