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
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.
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 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:
That’s all. Thanks for reading. ?
$name = 'Adam'; $text = <<<'TEXT' My name is $name TEXT; echo $text; // output: 'My name is $name'
Preview may take a few seconds to load.
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Bold **double asterisks**
Three back ticks and then enter your code blocks here.
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
> type a greater than sign and start typing your quote.
You can add links by adding text inside of  and the link inside of (), like so:
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of , and the image URL inside of (), like so:
To add a divider you can add three dashes or three asterisks:
--- or ***