PHP Echo / Print

La Lakshmi Priya Updated 29 Oct 2026
10 min read

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.

Data Mining
Introduction to Data Mining Data Mining Implementation Process Data Mining Architecture Data Mining Techniques KDD: Knowledge Discovery in Databases History of Data Mining Data Mining Tools Data Mining vs Machine Learning Facebook Data Mining Social Media Data Mining Methods Clustering in Data Mining Text Data Mining Bagging vs Boosting Data Mining vs Data Warehousing Social Media Data Mining Data Mining: Bayesian Classifiers Data Mining: World Wide Web Different Types of Clustering Bitcoin Mining and Blockchain Data Mining Orange Data Mining Data Mining vs Big Data Decision Tree Induction Educational Data Mining Data Mining in Healthcare Apriori Algorithm Data Integration in Data Mining Difference Between Data Mining and Text Mining Discretization in Data Mining Redundancy and Correlation in Data Mining Classification of Data Mining Systems Classification Algorithms in Data Mining Data Generalization in Data Mining Classification and Prediction in Data Mining Regression in Data Mining What Is an Outlier in Data Mining Data Cleaning in Data Mining Data Processing in Data Mining Data Mining Task Primitives Web Content Mining, Web Structure Mining, and Web Usage Mini Binning in Data Mining KDD vs. Data Mining Noise in Data Mining BIRCH in Data Mining Stemming in Data Mining Feature Transformation in Data Mining Visual and Audio Data Mining Class Comparison Methods in Data Mining Data Selection in Data Mining Tasks and Functionalities of Data Mining Ubiquitous and Invisible Data Mining Importance of Data Mining Data Quality in Data Mining Mining Frequent Patterns in Data Mining Data Warehouse and OLAP Technology for Data Mining Need for Data Mining Pattern Evaluation Methods in Data Mining Logarithms and Exponents in Complexity Analysis Time Series Clustering What is the C4.5 Algorithm and How Does It Work? Expanding Contractions in Text Mining Cosine Similarity in Data Mining Lazy Learning in Data Mining Neural Networks in Data Mining Building a Text Normalizer Shallow Parsing Data Pipeline Orchestration Big Data vs Small Data Myths of Data Mining Data Reduction in Data Mining Data Mining Models Difference Between Data Mining and Data Science Difference Between Data Mining and Statistics Difference Between Data Mining and Web Mining Difference Between Data Mining and Data Analysis Difference Between Business Intelligence and Data Mining Difference Between Data Mining and Data Visualization Data Mining vs Data Analytics Types of Data Mining Difference Between Data Profiling and Data Mining Predictive Analytics vs Data Mining Difference Between Data Mining and OLAP Descriptive and Predictive Data Mining Difference Between Spatial and Temporal Data Mining Difference Between Classification and Clustering in Data Min Hierarchical Clustering in Data Mining Density-Based Clustering in Data Mining What Is Aggregation in Data Mining?
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.