- Instant help with your Php coding problems

PHP heredoc syntax

Heredoc is a robust way to create a 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, 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:

<?php
   $str = <<<DEMO
This is a
demo message
with heredoc.
DEMO;
 
   echo $str;
?>

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:

<?php
   $name = "Max";
   $str = <<<DEMO
Hello $name! <br/>
This is a
demo message
with heredoc.
DEMO;
 
   echo $str;
?>

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

Share "PHP heredoc syntax" with your friends