← Back to PHP Course | Chapter 6: Strings | Lesson 6 of 8

PHP heredoc & nowdoc

Understanding Heredoc

Heredoc syntax (<<<EOT ... EOT) lets you write a multi-line string without escaping every quote, while still interpolating variables inside it just like a double-quoted string would. It's handy for embedding a block of HTML or a long message directly in PHP code.

Example: Understanding Heredoc

php
<?php
$name = "Alice";
$text = <<<EOT
Hello, $name!
Welcome to PHP.
EOT;
echo $text;
?>

Understanding Nowdoc

Nowdoc syntax (<<<EOT ... EOT, note the single quotes around the identifier) works like heredoc but never interpolates variables, behaving exactly like a single-quoted string spread across multiple lines. Reach for it when your multi-line text contains literal $ characters you don't want PHP to try to expand.

Example: Understanding Nowdoc

php
<?php
$name = "Alice";
$text = <<<'EOT'
Hello, $name!
This is literal, not interpolated.
EOT;
echo $text;
?>

Multiline Block Generation

The closing identifier must start at the beginning of its own line in older PHP versions, though PHP 7.3+ relaxed this to allow indentation matching the opening marker, making heredoc/nowdoc blocks easier to keep neatly indented inside functions.

Example: Multiline Block Generation

php
<?php
function greet() {
    $msg = <<<EOT
    Hello!
    This is indented heredoc (PHP 7.3+).
    EOT;
    return $msg;
}
echo greet();
?>

Escaping Rules inside Heredoc

Because heredoc supports interpolation, you can embed variables and even simple expressions like {$array[key]} directly inside the block, which keeps templated text readable compared to concatenating dozens of string pieces with dots.

Example: Escaping Rules inside Heredoc

php
<?php
$data = ['key' => 'Alice'];
$text = <<<EOT
Name: {$data['key']}
EOT;
echo $text;
?>

Flexible Indentation

Heredoc and nowdoc are commonly used for embedding SQL queries, JSON payloads, or HTML fragments where the text is long and full of quote characters that would otherwise need constant escaping in a normal quoted string.

Example: Flexible Indentation

php
<?php
$name = "Alice";
$json = <<<EOT
{"name": "$name", "active": true}
EOT;
echo $json;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.