PHP Echo / Print

La Lakshmi Priya Updated 30 Oct 2026
10 min read ·Lesson 203 of 209

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"; and echo("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 echo as a callback to array_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 echo outputs a double-quoted string. $course is replaced with its value and \n adds a line break.
  • The second echo receives 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 \n must 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

Featureechoprint
Number of argumentsOne or more, separated by commasExactly one
Return valueNone — it is a statementAlways returns 1
Can be used inside an expressionNoYes
SpeedMarginally faster (no return value)Marginally slower — the difference is irrelevant in practice
Common usageThe standard choice in almost all codeRare; 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

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 "...", the print runs only when $isDebug is true, because && stops evaluating as soon as the left side is false ("short-circuit" evaluation).
  • $result receives the return value of print, which is 1.

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 echo outputs 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"));
  1. The argument of the first print is the entire expression ("Hello") && print("World").
  2. To evaluate &&, PHP evaluates "Hello" (truthy) and then print("World"), which outputs World and returns 1.
  3. "Hello" && 1 evaluates to true.
  4. The first print outputs true, 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: 
ValueOutput as String
Integer 4242
Float 3.503.5 (no trailing zeros)
true1
falseempty string
nullempty 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

  1. Comma-separated echo arguments combine fixed HTML with dynamic values without building intermediate strings.
  2. htmlspecialchars() escapes customer and product names, so characters like < or & in the data cannot break the HTML or inject scripts.
  3. A foreach loop outputs one <li> per item.
  4. number_format($total, 2) produces 3,497.50 — two decimal places with a thousands separator — instead of PHP's default 3497.5.
  5. The \n characters 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() and setcookie() must be called before any echo.
  • 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 echo as the default output statement; reserve print for the rare cases where a return value is needed.
  • Write echo without parentheses to make it clear it is not a function.
  • Use commas or parentheses when mixing concatenation and arithmetic.
  • Use var_dump() — not echo — to inspect values while debugging.
  • Escape all external data in HTML output.
  • For formatted numbers, use number_format() or printf().

Official reference: https://www.php.net/manual/en/function.echo.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PHP XML Parsers PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions
Ask about this post
AI Ask about this post

Ask questions about PHP Echo / Print and get answers drawn from it.

Signed-in readers only.