Skip to content

PHP Tutorial Strings

Heredoc and Nowdoc

Lesson 60 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

For text that runs over many lines, such as an email body or a block of HTML, quotes get messy. Heredoc and nowdoc are made for this.

Heredoc: like double quotes

A heredoc starts with <<< and a name (the marker). It ends when the same name appears again on its own line.

index.php
PHP
<?php
$name = "Priya";
$order = 1042;

echo <<<TEXT
Hello $name,

Your order #$order has shipped.

Thank you!
TEXT;
Output
OUTPUT
Hello Priya,

Your order #1042 has shipped.

Thank you!

Variables are replaced, and quotes inside need no escaping.

Nowdoc: like single quotes

A nowdoc looks the same, but the marker is wrapped in single quotes. Nothing is replaced.

index.php
PHP
<?php
echo <<<'CODE'
Use $name to print the name.
Line two: \n is not a new line here.
CODE;
Output
OUTPUT
Use $name to print the name.
Line two: \n is not a new line here.

Nowdoc is handy for showing code samples and templates.

Indented closing marker

Since PHP 7.3 you may indent the closing marker. PHP then removes that same indentation from every line, so you can keep the code tidy.

index.php
PHP
<?php
function welcome(string $name): string
{
    return <<<HTML
        <h1>Welcome, $name</h1>
        <p>Glad you are here.</p>
        HTML;
}

echo welcome("Priya");
Output
OUTPUT
<h1>Welcome, Priya</h1>
<p>Glad you are here.</p>

The closing HTML; has 8 spaces, so 8 spaces are removed from each line above it.

Rules

  • The opening line is <<<MARKER with nothing after it.
  • The closing marker must be alone on its line (it can be indented). A ; or , can follow it.
  • Every line of the text must be indented at least as far as the closing marker.

Expressions

You can use {$var} and {$array['key']} just like in double quotes.

index.php
PHP
<?php
$user = ["name" => "Priya", "role" => "admin"];

echo <<<INFO
Name: {$user['name']}
Role: {$user['role']}
INFO;
Output
OUTPUT
Name: Priya
Role: admin
lightbulb
Heredoc is fine for small templates only
If you write a lot of HTML inside PHP strings, use a real template file instead. See Header and Footer Components.