2

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.

ADyson
  • 57,178
  • 14
  • 51
  • 63
amd_123
  • 41
  • 3
  • I always use brackets `{$var}`. This also makes it possible to use more advanced variables, such as object members `{$myobj->property}` or array references `{$myarr[123]}` – Gowire Nov 02 '22 at 12:54
  • 2
    Please read the official docs where this question gets resolved: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing – Gonzalo Nov 02 '22 at 13:04

1 Answers1

3

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

ADyson
  • 57,178
  • 14
  • 51
  • 63