Reputation: 1147
I'm quite a beginner when it comes to the ternary operators, never worked with them before.
Code (it was simplified)
$output2 = '
<div>
<div>
<span>test text1</span>
<div>
'.(1 == 1) ? "yes" : "no" .'
<span>test text 2</span>
</div>
</div>
</div>';
echo $output2;
So the problem is, this code only outputs "yes" (only the correct or false if statement)
I tried with ""
same problem, tried with different conditions, tried just outputing it, without variables. But the problem remains.
Upvotes: 1
Views: 2902
Reputation: 2582
Alexander's answer is correct, but I would go a little further and actually remove the ternary from the string.
$ternary = ($something == $somethingElse) ? "yes" : "no";
// Double brackets allows you to echo variables
// without breaking the string up.
$output = "<div>$ternary</div>";
echo $output;
Doing it this way proves to be much easier to maintain, and reuse.
Here are a few uses for ternary operators. They're very powerful if you use them properly.
Upvotes: 2
Reputation: 54841
In php ternary operator behaves strangely, in your case:
(1 == 1) ? "yes" : "no" .'<span>test text 2</span>...'
yes
is considered the first result, and "no" . <span>test text 2</span>...
is the second result. To avoid such behaviour always use brackets
((1 == 1) ? "yes" : "no") .'<span>test text 2</span>...' // works correctly
Upvotes: 7
Reputation: 2339
Surround your ternary if
with brackets, i.e.
$output2 = '
<div>
<div>
<span>test text1</span>
<div>
'.((1 == 1) ? "yes" : "no") .'
<span>test text 2</span>
</div>
</div>
</div>';
echo $output2;
Upvotes: 9