Home / PHP’s heredoc strings

PHP’s heredoc strings

PHP has heredoc syntax similar to other programming and scripting languages which allow multi line strings containing variables to be easily assigned to variables or echoed. This post looks at how to format a heredoc block in PHP and some of the rules.

Heredoc Example

$string = <<<END_OF_STRING
    this is a multi-line
    string containing $variables
    and single quotes '
    and double quotes "
    and slashes 
    do not need to be escaped

The rules

A heredoc block starts with <<< and then a block identifier. It then ends with the name of the block identifier followed by a semi-colon. In the above example the identifier is "END_OF_STRING".

The closing identifier must start on a new line, and there must not be any white space between the start of the line and the start of the label name, otherwise the heredoc block does not end.

The identifier can contain any alpha-numeric character and underscores, and must start with a non-numeric character or an underscore.

Identifier names are case-sensitive.

Single quotes ‘, double quotes " and slashes do not need to be escaped.

Variables are expanded as for a double quoted string.


Nowdoc works similarly to heredoc but treats the string like a single quoted string. They were introduced in PHP 5.3.0 and I will look at them another time.