I tried this but only got a syntax error:
<?php
$a = true;
$str = <<< EOF
{$a ? 1 : 2}
EOF;
echo $str;
Is it possible to use such kind of conditional statement inside heredoc?
Nope. PHP string interpolation is, unfortunately, not quite that robust. You'll either have to concatenate two strings, or assign that little bit of logic to another variable ahead of time.
<?php
$a = true;
$b = $a ? 1 : 2;
$str = <<<EOF
Hello, world! The number of the day is: $b
EOF;
echo $str;
I would say no.
See this related question on why you can't do function calls and possible workarounds: Calling PHP functions within HEREDOC strings
The crux of it is that you will probably have to assign your ternary operator to a variable before the heredoc.
FWIW you can use heredocs as either half of a ternary. As the :
/else case,
$optional_input = empty($name) ? "" : <<<INPUT
<input type="hidden" name="name" value="$name" />
INPUT;
and if you don't mind avant garde syntax, as the ?
/if case:
$optional_input = isset($name) ? <<<INPUT
<input type="hidden" name="name" value="$name" />
INPUT
: "";
For the ?
/if case, the heredoc's closing delimiter (INPUT
) does need to be on its own line; the :
's indentation is for clarity.
You could do something like this:
$values = array('1', '2');
$str = <<<EOF
{$values[$a]}
EOF;