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;
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With