Difference Between Heredoc and Nowdoc in PHP
PHP offers multiple ways to define strings, including Heredoc and Nowdoc syntaxes, which are ideal for outputting large blocks of text without the need for extensive escaping. While they look similar structurally, the fundamental difference lies in how they handle variable parsing and escape sequences. This article provides a clear, direct comparison of Heredoc and Nowdoc in PHP, detailing their syntax, behavior, and practical use cases.
Heredoc Syntax (Double-Quoted Behavior)
Heredoc syntax behaves exactly like a double-quoted string. This
means that any PHP variables placed inside a Heredoc string will be
parsed and replaced with their actual values. Similarly, escape
sequences (like \n for a new line or \t for a
tab) will be interpreted.
Syntax and Example
To define a Heredoc string, use the opening operator
<<< followed by an identifier. The identifier is
not enclosed in single quotes.
<?php
$name = "Alice";
// Heredoc syntax
$heredocString = <<<EOT
Hello, $name!
Welcome to the PHP guide.
EOT;
echo $heredocString;
// Output:
// Hello, Alice!
// Welcome to the PHP guide.
?>Nowdoc Syntax (Single-Quoted Behavior)
Nowdoc syntax behaves exactly like a single-quoted string. It does not parse variables or escape sequences. The text inside a Nowdoc is treated as a literal string. This makes it highly efficient and safe for storing raw blocks of code, configuration files, or text templates that contain characters that might otherwise be interpreted by PHP.
Syntax and Example
To define a Nowdoc string, use the opening operator
<<< followed by an identifier enclosed in single
quotes: 'IDENTIFIER'.
<?php
$name = "Alice";
// Nowdoc syntax
$nowdocString = <<<'EOT'
Hello, $name!
Welcome to the PHP guide.
EOT;
echo $nowdocString;
// Output:
// Hello, $name!
// Welcome to the PHP guide.
?>Key Differences At a Glance
| Feature | Heredoc
(<<<EOT) |
Nowdoc
(<<<'EOT') |
|---|---|---|
| Equivalent to | Double-quoted string
("...") |
Single-quoted string
('...') |
| Variable Parsing | Yes (e.g., $variable is
evaluated) |
No (treated as literal text) |
| Escape Sequences | Yes (e.g., \n,
\t are processed) |
No (treated as literal text) |
| Syntax Marker | Identifier is unquoted (or double-quoted) | Identifier must be enclosed in single quotes |
| Best Used For | Dynamic HTML templates, formatted text with variables | Raw text, SQL queries, embedded code blocks (JS, HTML) |
When to Use Which?
Use Heredoc when you need to output multi-line strings that incorporate dynamic data from PHP variables, or when you need control over formatted spacing using escape sequences.
Use Nowdoc when you need to define large blocks of text that must remain exactly as written without any risk of PHP parsing. It is ideal for storing SQL queries, Javascript snippets, or HTML structures where you do not want PHP to accidentally interpret symbol patterns as variables.