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
Category:Basics
Level:Beginner

Bookmark PHP heredoc syntax



Bookmark and Share

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:

Code:
  1. <?php
  2. $str = <<<DEMO
  3. This is a
  4. demo message
  5. with heredoc.
  6. DEMO;
  7.  
  8. echo $str;
  9. ?>
Output:
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:

Code:
  1. <?php
  2. $name = "Max";
  3. $str = <<<DEMO
  4. Hello $name! <br/>
  5. This is a
  6. demo message
  7. with heredoc.
  8. DEMO;
  9.  
  10. echo $str;
  11. ?>
Output:
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
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.0403