PHP Heredoc & Nowdoc With Examples

In this article, we are going to learn PHP heredoc and nowdoc strings to improve the readability of the code. Let’s get started:

Table of Contents

  1. Mutliple Strings
  2. Herodoc
  3. Nowdoc

Mutliple Strings

Usually, we write multiple strings like this one:

$html = '<ul>';
$html .= '<li>product 1</li>';
$html .= '<li>product 2</li>';
$html .= '<li>product 3</li>';
$html = '</ul>';

echo $html;

Have a look at another example:

$he = 'Adam';
$text = "$he said, \"PHP is awesome".
echo $text;

Using herodoc and nowdoc we can write same code in the cleanest way.

Herodoc

Heredoc and nowdocs are the cleanest ways to format multiline strings in PHP. Heredoc strings are like double-quoted strings without escaping. Have a look at Heredoc structure:

$variable = <<<IDENTIFIER
YOUR CODE/TEXT GOES HERE
IDENTIFIER;

Now take a look at an example:

$html = <<<HTML
<ul>
    <li>product 1</li>
    <li>product 2</li>
    <li>product 3</li>
</ul>
HTML;

echo $html;

Let’s take a look at another example:

$he = 'Adam';

$text = <<<TEXT
$he said<br>
PHP is awesome
TEXT;

echo $text;

Nowdoc

Nowdoc strings are like single-quoted strings without escaping. In nowdoc variable names remain intact. Have a look at the structure:

$variable = <<<'IDENTIFIER' //  single quotes around identifier
YOUR CODE/TEXT GOES HERE
IDENTIFIER;

Have a look at an example:

$name = 'Adam';
$text = <<<'TEXT'
My name is $name
TEXT;

echo $text;
// output: 'My name is $name'

That’s all. Thanks for reading.