PHP heredoc syntax

Home - Tutorials - Basics

In this article I will show you how to use PHP heredoc syntax to create strings.  

Tutorial info:

Name:PHP heredoc syntax
Total steps:1

Bookmark PHP heredoc syntax

Step 1 - PHP heredoc syntax

PHP heredoc syntax

Heredoc is a robust way to create string in PHP with more lines but without using quotations. Heredoc is rarely used as the day by day usage is more complicated as creating strings with quotes or double quotes. Besides this the not properly used heredoc can lead to problems in your code.

However if you want to use it you can do it in the following way:

  1. <?php
  2. $str = <<<DEMO
  3. This is a
  4. demo message
  5. with heredoc.
  6. DEMO;
  8. echo $str;
  9. ?>
This is a demo message with heredoc.

As you see the heredoc starts with the <<< operator and an identifier. After it you can type your text in more lines as if it were a double quoted string. It means that you can use variables inside the heredoc. If you are ready with your text you only need to write the identifier again in a new line as follows:

  1. <?php
  2. $name = "Max";
  3. $str = <<<DEMO
  4. Hello $name! <br/>
  5. This is a
  6. demo message
  7. with heredoc.
  8. DEMO;
  10. echo $str;
  11. ?>
Hello Max! This is a demo message with heredoc.

Don't forget that it is not allowed to indent the closing tag if you do so you will get a parsing error. 

Tags: php heredoc syntax, php heredoc, heredoc syntax, heredoc

PHP heredoc syntax - Table of contents
Step 1 - PHP heredoc syntax

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.1422