Can we use PHP iF Statements in <<<EOD syntax code
Solution 1
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;
Solution 2
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;
Solution 3
No, but you can use variable substitions
if(isset($variablename))
{
$var "...some text";
}
else
{
$var "...some text";
}
<<<EOD
<h3>Caption</h3>
$var
EOD;
Solution 4
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)
Kiran Tangellapalli
I am a Senior Front End Developer, specialized in Angular, React, Javascript, Jquery, Bootstrap, Html/CSS
Updated on June 11, 2022Comments
-
Kiran Tangellapalli over 1 year
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;