Вопрос

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