Search code examples
phpconditional-operator

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.


Solution

  • 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;