Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use A ? x:y syntax with heredoc in PHP?

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?

like image 703
wamp Avatar asked Jun 10 '10 04:06

wamp


2 Answers

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;
like image 172
Matchu Avatar answered Nov 15 '22 04:11

Matchu


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.

like image 43
Matt Mitchell Avatar answered Nov 15 '22 03:11

Matt Mitchell