Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use PHP iF Statements in <<<EOD syntax code [closed]

Tags:

syntax

php

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;
like image 296
Kiran Tangellapalli Avatar asked May 09 '13 16:05

Kiran Tangellapalli


Video Answer


2 Answers

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;
like image 91
Spudley Avatar answered Nov 13 '22 01:11

Spudley


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;
like image 20
mario Avatar answered Nov 12 '22 23:11

mario