PHP: String Syntax, Heredoc

By Xah Lee. Date: . Last updated: .

String can be quoted by a single quote.

<?php
echo 'sweet home';

String can also be quoted using a double quote. When using double quote, any variables in the form $variableName or ${variableName} will be evaluated and its value used.

<?php
$x = 3;
echo "I bet you\n ${x} dollars";

/* output:
I bet you
 3 dollars
 */

Escape character sequence such as {\n, \r, \t} will also be interpreted when using double quote.

Heredoc and Nowdoc: Quoting Long Text

If you have a large block of text, you can use a form called “heredoc”.

You start the quote delimiter by <<<anyLetterSequence and end it by the same letter sequence, followed by a semicolon, on a line by itself. Example:

<?php
$herName = 'Alice';

$longText = <<<mbcfxq
'and what is the use of a book,' thought $herName
'without pictures or conversation?'.
mbcfxq;

echo $longText;

The output of above is this:

'and what is the use of a book,' thought Alice
'without pictures or conversation?'.

Note that in the above, we used this random string: mbcfxq for the delimiter. The ending delimiter must be exactly that followed by a semicolon, on a line by itself. No other chars can be there.

Heredoc is especially useful for large block of text (such as a template) that may itself contain many single quotes or double quotes.

Variables inside heredoc will still be interpreted (replaced by their values). Same for escape sequences (For example, {\n, \t, …}).

Nowdoc: Literal Quoting

To not have variables interpreted, use a form called “nowdoc”. The syntax is the same as heredoc, except you start it like this <<<'anyLetterSequence'. Example:

<?php
$herName = 'Alice';

$longText = <<<'mbcfxq'
'and what is the use of a book,' thought $herName
'without pictures or conversation?'.
mbcfxq;

echo $longText;

The output of above is this:

'and what is the use of a book,' thought $herName
'without pictures or conversation?'.

If you have a question, put $5 at patreon and message me.

  1. PHP Install
  2. PHP Basics
  3. String Syntax
  4. String Operations
  5. Array
  6. Hash Table
  7. Looping Thru Array
  8. Function
  9. Write Package
  10. Send HTML Mail
  11. Send Mail with Attachment
  12. MySQL Database Query