Thuta Learning
PHP
BasicProgrammingBeginner

Echo & Print

PHPLesson 630 min

What you'll walk away with

  • Choose between `echo`, `print` and `printf`/`sprintf` and know what each returns
  • Predict the output of single-quoted and double-quoted strings, including escapes and `{$var}` interpolation
  • Write multi-line text with heredoc and nowdoc and use `PHP_EOL`
  • Escape user data with `htmlspecialchars()` before printing it into HTML

Explain it simply

Output in plain words

PHP produces results by 'saying' them out loud. `echo` is the everyday way, `print` does nearly the same with one quirk, and `printf` fills values into a formatted template. In a terminal the output appears on screen, and on the web it becomes part of the page.

Also learn the two kinds of quotes first. Text inside single quotes (`'...'`) is printed exactly as typed. Inside double quotes (`"..."`) PHP fills in the values of variables and honours special characters such as `\n`.

Problem → Why → Solution

The problem: the output is not what you expected

The script below looks simple, yet its output disappoints in three places. The first line does not print `Hello Aye Aye`; it prints the characters `$name\n` exactly as typed. The next two `echo` calls have no line break, so their text continues on one line. The last `echo $items` raises `Warning: Array to string conversion` and prints only the word `Array`.

Nothing crashes, and PHP does exactly what it was told. The problem is not knowing what `echo` does for you and what it does not.

output.php
<?php
$name = "Aye Aye";
$items = ["tea", "coffee"];

echo 'Hello $name\n';     // prints the characters: Hello $name\n
echo "Hello, ";            // no newline, so the next echo continues this line
echo $name;
echo $items;               // Warning: Array to string conversion, then "Array"

What echo does not do for you

`echo` prints exactly the text it is given: it adds no line break, looks up no variable inside single quotes and cannot turn an array into text. Knowing which quote and which function to choose avoids all of these surprises.

Core concept: the output constructs and the two kinds of quotes

`echo` and `print` are language constructs, not functions, so parentheses are optional. `echo` accepts several comma-separated arguments and returns nothing. `print` takes exactly one argument and returns 1, so it can appear inside an expression such as `$ok = print "x";`. Both write to the output: the terminal in the CLI and the response body on the web. In practice `echo` is the one you use.

SyntaxVariables filled inEscape sequencesTypical use
`'single'`NoOnly `\'` and `\\`Fixed text, regular expressions
`"double"`Yes`\n`, `\t`, `\"`, `\$`, `\u{...}`Messages that contain values
`<<<TXT` heredocYesSame as double quotesMulti-line templates
`<<<'TXT'` nowdocNoNoneMulti-line raw text

Inside double quotes a plain variable such as `$name` can be written directly. For array items and object properties use braces, as in `{$array['key']}` and `{$object->property}`, so it is obvious where the variable name ends. Nesting quotes, as in `"$user["role"]"`, is a parse error. The old `${name}` style has been deprecated since PHP 8.2 and shows `Deprecated: Using ${var} in strings is deprecated, use {$var} instead`.

For tidy formatting use `printf()` and `sprintf()`, which fill placeholders such as `%s` (string), `%d` (integer) and `%.2f` (two decimals). `printf` prints immediately and returns the number of characters written, while `sprintf` prints nothing and returns the string instead. Use `PHP_EOL` for line breaks; it is `"\n"` on Linux and macOS and `"\r\n"` on Windows.

A simple rule keeps the choice easy. Use `echo` with commas for everyday output, `printf` when layout matters (columns, decimals, padding), `sprintf` when you need the text as a value to store or return, and heredoc when the text spans many lines. Reach for `print` only when you need it inside an expression. Joining with `.` also works, but note that in PHP 8 `+` binds tighter than `.`, so `"Total: " . 5 + 3` prints `Total: 8`.

A mental model: build the string, then send it out
  1. Pick echo, print or printf
  2. PHP builds the string first
  3. Double quotes fill in variables
  4. The text goes to terminal or browser

The quote type decides how the string is built; echo and print only send out the finished string.

General pattern: ways to produce output

php
<?php
echo $value, "text", PHP_EOL;          // several arguments, no return value
$one = print "text";                   // one argument, returns 1
printf("%s has %d items", $text, $count);
$line = sprintf("%.2f", $number);      // build a string instead of printing it
echo "Hello {$array['key']}";          // interpolation inside double quotes

`echo` prints many comma-separated values. `print` prints one and returns 1. `printf` fills a template and prints it, while `sprintf` returns it as a string. Inside double quotes `{$array['key']}` inserts a value from an array.

Example: echo, print, quotes and printf

This script uses the output methods one after another: `echo` with commas, the return value of `print`, a comparison of the two quote kinds, and finally formatting with `printf`. Predict each line's output before you run it.

output.php
<?php
declare(strict_types=1);

$course = "PHP";
$platform = "ThutaTech";
$lessons = ["intro" => 2, "variables" => 5];

echo "Learn ", $course, PHP_EOL;
$returned = print "Practice with {$platform}" . PHP_EOL;
echo "print returned ", $returned, PHP_EOL;

echo 'Single quotes keep $course as text', PHP_EOL;
echo "Double quotes put {$course} in: lesson #{$lessons['variables']}", PHP_EOL;
printf("%s costs %05.1f for %d lessons%s", $course, 9.5, count($lessons), PHP_EOL);

Code breakdown

  1. echo with several argumentsecho "Learn ", $course, PHP_EOL;

    `echo` prints the three comma-separated items in order. This is tidier than joining with `.` and avoids building a new string.

  2. print returns 1$returned = print "Practice with {$platform}" . PHP_EOL;

    `print` outputs the line and returns 1, which lands in `$returned`; the next line prints it. `echo` cannot do this.

  3. Single quotes are literalecho 'Single quotes keep $course as text', PHP_EOL;

    Inside single quotes `$course` is not treated as a variable, so the characters `$course` appear in the output.

  4. Double quotes and bracesecho "Double quotes put {$course} in: lesson #{$lessons['variables']}", PHP_EOL;

    `{$course}` inserts the variable's value `PHP`, and `{$lessons['variables']}` inserts the value `5` stored under the key `variables`. The braces are what allow the inner quotes.

  5. printf placeholdersprintf("%s costs %05.1f for %d lessons%s", $course, 9.5, count($lessons), PHP_EOL);

    `%s` is for a string, `%05.1f` means one decimal in a width of five padded with zeros, and `%d` is for a whole number. That is why `9.5` becomes `009.5`. The final `%s` is filled with `PHP_EOL`.

You should see
Learn PHP
Practice with ThutaTech
print returned 1
Single quotes keep $course as text
Double quotes put PHP in: lesson #5
PHP costs 009.5 for 2 lessons

Heredoc and nowdoc

Multi-line text such as an email body or an HTML fragment can be written with heredoc, with no need to escape quotes. It starts with `<<<TEXT` and ends with `TEXT;`, and variables are filled in just as in double quotes. Nowdoc (`<<<'TEXT'`) fills in nothing, like single quotes. Since PHP 7.3 the closing marker may be indented, and that indentation is removed from every line.

heredoc.php
<?php
$name = "Aye Aye";
$items = ["tea" => 2500];

echo <<<TEXT
    Dear {$name},
    A cup of tea costs {$items['tea']} MMK.
    TEXT;
echo PHP_EOL;

echo <<<'RAW'
    Nowdoc keeps $name and {$items['tea']} exactly as typed.
    RAW;
echo PHP_EOL;

The output is `Dear Aye Aye,` and `A cup of tea costs 2500 MMK.`, followed by `Nowdoc keeps $name and {$items['tea']} exactly as typed.`. The four spaces before the closing `TEXT;` are removed from every line.

printf placeholders

PlaceholderMeaningExample
`%s`string`%s` with `tea` gives `tea`
`%d`whole number`%d` with `12` gives `12`
`%.2f`two decimals`%.2f` with `3.14159` gives `3.14`
`%05d`width 5, zero padded`%05d` with `42` gives `00042`
`%-8s`left-aligned, width 8`tea` followed by five spaces
`%%`a literal percent sign`%%` gives `%`
format.php
<?php
declare(strict_types=1);

printf("%-8s|%5d|%8.2f|%05d|%x%%" . PHP_EOL, "tea", 12, 3.14159, 42, 255);
echo sprintf("%2\$s %1\$s", "world", "hello"), PHP_EOL;
echo number_format(1234567.891, 2), PHP_EOL;
echo str_pad("7", 3, "0", STR_PAD_LEFT), PHP_EOL;

The four output lines are `tea | 12| 3.14|00042|ff%`, `hello world`, `1,234,567.89` and `007`. A numbered form such as `%2$s %1$s` lets you use the arguments in a different order, which helps when word order differs between languages. `number_format()` adds thousands separators.

Printing arrays and debugging

`echo` cannot print an array; you only get the word `Array`. For reading, `print_r()` shows the structure, while `var_dump()` also shows the types and lengths. `var_export()` gives output that can be pasted back as PHP code. With `print_r($x, true)` and `var_export($x, true)` the second argument `true` returns the text instead of printing it.

debug.php
<?php
$user = ["name" => "Aye", "tags" => ["php", "sql"], "active" => true];

print_r($user);
var_dump($user["active"], $user["tags"]);
echo var_export($user["tags"], true), PHP_EOL;

`print_r` prints the layout `Array ( [name] => Aye [tags] => Array (...) [active] => 1 )` over several lines; note that it shows true as `1`. `var_dump` prints `bool(true)` followed by `array(2) { ... }`. Use `var_dump` for debugging and `print_r` when you want a quick readable dump. Never leave such debug output on a production page.

Escaping what you print

When a value printed into an HTML page comes from a user (a comment, a name, a search term) rather than from your own code, it may contain characters such as `<script>`. Echoing it without escaping lets the browser run that code, which is called XSS (cross-site scripting). `htmlspecialchars()` replaces `<`, `>`, `&` and quotes with their HTML entity forms, so the value shows up as plain text.

escape.php
<?php
declare(strict_types=1);

$comment = '<script>alert("hi")</script> & "quotes"';

echo "Unsafe:  ", $comment, PHP_EOL;
echo "Escaped: ", htmlspecialchars($comment, ENT_QUOTES, "UTF-8"), PHP_EOL;

In the second output line below, the `<` and `>` of `<script>`, the `&` and the quotes have turned into entities, so the browser shows the text instead of running it as a script. Writing the flags and charset explicitly, as in `ENT_QUOTES, "UTF-8"`, keeps the code correct on every PHP version. Do the escaping at the last moment, when the value is printed.

output
Unsafe:  <script>alert("hi")</script> & "quotes"
Escaped: &lt;script&gt;alert(&quot;hi&quot;)&lt;/script&gt; &amp; &quot;quotes&quot;

In real projects

Output in real projects

Plain PHP templates use `echo` constantly, and every value that did not come from your own code must be escaped. Template engines do this automatically: Blade's `{{ $name }}` in Laravel and Twig escape by default, and unescaped output needs a deliberate syntax such as Blade's `{!! !!}`.

Command-line tools use `printf` to line up columns, and APIs print JSON with `echo json_encode($data);` after sending a `Content-Type` header. Errors and log lines normally go to a file through `error_log()` instead of the screen, so 'what do I print, and where does it go?' is the first question to ask about any output. Keeping output code in one place, such as a view function or a template file, also makes it much easier to review that every value is escaped.

Common mistakes

Common beginner mistakes

1. Expecting variables inside single quotes

`echo 'Hello $name\n';` does not print `Hello Aye Aye` and a line break; it prints `Hello $name\n`. Use double quotes when you need a variable or `\n`, or join pieces as in `echo 'Hello ' . $name . PHP_EOL;`.

2. Expecting `\n` to break a line in the browser

In a terminal `\n` and `PHP_EOL` start a new line, but HTML treats line breaks like a single space. To break a line in the browser, output `<br>` or tags such as `<p>` and `<li>`. Also remember that `PHP_EOL` is `\r\n` on Windows, so code that measures lengths can differ from machine to machine.

3. Printing an array with echo

`echo $items;` raises `Warning: Array to string conversion` and prints only `Array`. Use `print_r($items);` to read it, `var_dump($items);` to debug, `implode(", ", $items)` to join the values into one line, or `json_encode($items)` for an API.

4. Printing user data without escaping

Printing `echo $_GET["q"];` straight into HTML lets a link containing `<script>` run code in another user's browser. Any value that comes from a user (a URL, a form, a cookie, even text stored earlier in a database) must go through `htmlspecialchars()` before it is printed into HTML.

Mini challenge

Mini challenge: a receipt printer

Use `sprintf()`, `number_format()` and `printf()` to print a receipt with three items. Left-align the item name, show the quantity, and show each line total with a thousands separator and two decimals.

  • Write `receiptLine(string $item, int $qty, float $price): string` using `sprintf("%-10s x%-2d %10s", ...)`
  • Format the line total (`$qty * $price`) with `number_format(..., 2)`
  • Print each item inside a `foreach` and add up the grand total in `$total`
  • After a `str_repeat("-", 25)` line, print the `TOTAL` line with `printf()`
receipt.php
<?php
declare(strict_types=1);

// TODO: add the types: string $item, int $qty, float $price, and a string return type
function receiptLine($item, $qty, $price)
{
    // TODO: sprintf() the name (left aligned), "x<qty>" and the formatted line total
}

$items = [
    ["name" => "Tea", "qty" => 2, "price" => 1500.5],
    ["name" => "Mohinga", "qty" => 1, "price" => 2500.0],
    ["name" => "Coffee", "qty" => 3, "price" => 1200.25],
];

// TODO: print one receipt line per item and keep a running $total
// TODO: print a line of dashes, then the TOTAL line with printf()

Expected: Prints Tea x2 3,001.00, Mohinga x1 2,500.00 and Coffee x3 3,600.75 in aligned columns, then a dash line and TOTAL 9,101.75. Tea x2 3,001.00 Mohinga x1 2,500.00 Coffee x3 3,600.75 ------------------------- TOTAL 9,101.75

Show hint

`%-10s` left-aligns the name in ten characters and `%10s` right-aligns. `number_format()` returns a string, so insert it with `%s`. Accumulate the grand total with `$total += $row["qty"] * $row["price"];`.

Show solution
receipt.php
<?php
declare(strict_types=1);

function receiptLine(string $item, int $qty, float $price): string
{
    return sprintf("%-10s x%-2d %10s", $item, $qty, number_format($qty * $price, 2));
}

$items = [
    ["name" => "Tea", "qty" => 2, "price" => 1500.5],
    ["name" => "Mohinga", "qty" => 1, "price" => 2500.0],
    ["name" => "Coffee", "qty" => 3, "price" => 1200.25],
];

$total = 0.0;
foreach ($items as $row) {
    echo receiptLine($row["name"], $row["qty"], $row["price"]), PHP_EOL;
    $total += $row["qty"] * $row["price"];
}

echo str_repeat("-", 25), PHP_EOL;
printf("%-14s %10s" . PHP_EOL, "TOTAL", number_format($total, 2));

Quick quiz 1 / 3

What does `$n = 'Ko'; echo 'Hi $n', PHP_EOL;` print?

Quick quiz 2 / 3

Which statement about `print` is true?

Quick quiz 3 / 3

Which line prints a user-submitted comment safely inside an HTML page?

What to remember

  • `echo` prints many arguments, `print` prints one and returns 1, `printf` formats and `sprintf` returns a string
  • Single quotes are literal, double quotes fill in variables and `\n`, and `{$array['key']}` handles array items
  • Use heredoc for multi-line templates and nowdoc for raw text where nothing should be filled in
  • Always escape data from users with `htmlspecialchars()` before printing it into HTML

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Echo & Print | Thuta Learning