6

I am using <<<EOD to output some data. My question is how to use php if condition inside the <<<EOD syntax? can i use it like this

 <<<EOD
<h3>Caption</h3>
if(isset($variablename))
{
echo "...some text";
}
else
{
echo "...some text";
}
EOD;
Spudley
  • 166,037
  • 39
  • 233
  • 307
Kiran Tangellapalli
  • 162
  • 1
  • 1
  • 12

5 Answers5

13

No, because everything inside the <<< block (known as a "HEREDOC") is a string.

If you write the code in the question, you'll be writing a string containing PHP code, which isn't what you want (I hope).

Do your logic outside of the HEREDOC, and use plain variables inside it:

if(isset($variablename)) {
   $outputVar = "...some text";
} else {
    $outputVar = "...some text";
}

print <<<EOD
<h3>Caption</h3>
{$outputVar}
EOD;
Spudley
  • 166,037
  • 39
  • 233
  • 307
9

You can only use expressions, not statements, in double quoted strings.

There's a workaround in complex variable expressions however. Declare a utility function beforehand, and assign it to a variable.

$if = function($condition, $true, $false) { return $condition ? $true : $false; };

Then utilize it via:

echo <<<TEXT

   content

   {$if(isset($var), "yes", "no")}

TEXT;
Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291
  • Just a note: this solution requires PHP >= 5.3 if you want to use an anonymous function and not a named function. – G-Nugget May 09 '13 at 16:28
  • The expression syntax works with all PHP versions. The anonymous function could be displaced with a named function and plain string in the `$if` variable for PHP before 5.3. (Which is a good idea, since 5.3 just recently reached 50% server spread.) – mario May 09 '13 at 16:30
  • can we use html table in << – Kiran Tangellapalli May 09 '13 at 16:34
  • @kumar: That's a different question, and can also easily be googled or evaluated by trying out. – mario May 09 '13 at 16:35
  • This is the correct answer. Tested and it works! Thank you :] – tfont Aug 11 '15 at 15:40
2

No, but you can use variable substitions

if(isset($variablename))
{
$var "...some text";
}
else
{
$var "...some text";
}
<<<EOD
<h3>Caption</h3>
$var
EOD;
Anigel
  • 3,435
  • 1
  • 17
  • 23
1

No. Interpolation using the heredoc syntax is the same as when using double quotes. You can do simple interpolation of variables or class methods, but that's it.

This code

$foo = 'bar';
<<<EOD
$foo
baz($foo);
EOD;

will output

bar
baz(bar)
G-Nugget
  • 8,666
  • 1
  • 24
  • 31
0
<<<EOD
<h3>Caption</h3>
EOD;
if(isset($variablename))
{
echo "...some text";
}
else
{
echo "...some text";
}
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91