简体   繁体   中英

simple php code not working with ternary operator

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, ie

$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>... "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM