phpheredocnowdoc

How to include text next to php variable in heredoc text


My actual use case involves filling in javascript variable names with partial id's from php, but to illustrate the issue here's a simple example with html:

$var="ello worl";

echo <<<HTML

H$var d

HTML;

I want the output to be "Hello world" however of course there is a space after the $var variable name so the output is "Hello worl d". If I remove the space, then it changes the variable name.

How do I place text next to the right side of the variable?

I've tried quotes and escaping etc. but to no avail.


Solution

  • You can enclose the variable in curly braces ({ and }) to ensure the PHP interpeter knows which characters are part of the variable name and which are static text.

    $var="ello worl";
    
    echo <<<HTML
    
    H{$var}d
    
    HTML;
    

    Demo: https://3v4l.org/TYgEF

    Documentation reference: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing