1

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.

3
  • Well.. 1 does in fact equal 1, so yes should be returned. Commented Dec 1, 2013 at 16:44
  • yes, but it only returns "yes" and no "test text1" and "test text2" Commented Dec 1, 2013 at 16:45
  • Ah, I see what you mean now. Commented Dec 1, 2013 at 16:47

3 Answers 3

9

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;
Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.