문제

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.

Thank you.

Sebastjan

도움이 되었습니까?

해결책

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;

다른 팁

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

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top