7

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?

wamp
  • 5,789
  • 17
  • 52
  • 82

4 Answers4

9

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;
Matchu
  • 83,922
  • 18
  • 153
  • 160
3

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.

Community
  • 1
  • 1
Matt Mitchell
  • 40,943
  • 35
  • 118
  • 185
2

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.

Honore Doktorr
  • 1,585
  • 1
  • 13
  • 20
2

You could do something like this:

$values = array('1', '2');

$str = <<<EOF
{$values[$a]}
EOF;
Jimmer303
  • 21
  • 2