Search code examples
phpconcatenationheredoc

Concatenate string WITHIN a PHP HEREDOC block


I want to concatenate a string in a long(ish) HEREDOC block.

I am making a very quick and dirty form builder just to use to enter dummy data in the database. I have $var.Help in the text block:

$out = <<<textOnly
  <div class="form-group">
    <label for="$var">$var</label>
    <input type="text" class="form-control" id="$var" aria-describedby="$var" placeholder="$var">

    <small id="$var.Help" 

  class="form-text text-muted"> 
  We'll never share your email with anyone else.</small>
   </div>
textOnly;

If I do it with a space I get a space, if I do a dot I get a dot, no space looks for wrong variable and {} just causes an error. I know there are plenty of other ways to do this but is there a way to concatenate within a HEREDOC string?

TO CLARRIFY: I want to be able to do:

$var = fred;

in PHP. Then use that value in the line

<small id="$var.Help" 

to produce the result in HTML:

<small id="fredHelp" ...

Hope that is clearer.

Errors include:
$var.Help which just produces "fred.Help"
{$var.Help} produces error
$varHelp produces warning as looking for the variable $varHelp!


Solution

  • {$var}Help should do the trick. You delimit your var with the { and just add the string at the point it needs to be