PHP heredoc & nowdoc
In this page:
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
$name = "Alice";
$text = <<<EOT
Hello, $name!
Welcome to PHP.
EOT;
echo $text;
?>
Login to try C/C++/Java/PHP code in the editor
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
$name = "Alice";
$text = <<<'EOT'
Hello, $name!
This is literal, not interpolated.
EOT;
echo $text;
?>
Login to try C/C++/Java/PHP code in the editor
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
function greet() {
$msg = <<<EOT
Hello!
This is indented heredoc (PHP 7.3+).
EOT;
return $msg;
}
echo greet();
?>
Login to try C/C++/Java/PHP code in the editor
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
$data = ['key' => 'Alice'];
$text = <<<EOT
Name: {$data['key']}
EOT;
echo $text;
?>
Login to try C/C++/Java/PHP code in the editor
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
$name = "Alice";
$json = <<<EOT
{"name": "$name", "active": true}
EOT;
echo $json;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: