Polsonby
Polsonby

Reputation: 22875

Why is my ternary expression not working?

I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false.

$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge) { ?>Stuff<?php } ?>

What's up?

Upvotes: 26

Views: 1164

Answers (5)

Sohrab
Sohrab

Reputation: 131

You are using 'true' and 'false' as string. Using a string(non-empty and not '0' and not ' ', because these are empty strings and will be assume as false) as a condition will results the condition to be true.

I will write some correct conditions that could be use:

$canMerge = ($condition1 && $condition2);

$canMerge = ($condition1 && $condition2) ? true : false;

$canMerge = ($condition1 && $condition2) ? 'true' : 'false';
...
<?php if ($canMerge == 'true') { ?>Stuff<?php } ?>

Upvotes: 0

Anowar Hossain
Anowar Hossain

Reputation: 581

$canMerge = ($condition1 && $condition2);

then

if ($canMerge){
    echo "Stuff";
}

Upvotes: -1

depz123
depz123

Reputation: 507

Seems to me a reasonable question especially because of the discrepancy in the way PHP works.

For instance, the following code will output 'its false'

$a = '0';

if($a)
{
    echo 'its true';
}
else
{
    echo 'its false';
}

Upvotes: 0

Rudd Zwolinski
Rudd Zwolinski

Reputation: 27581

This is broken because 'false' as a string will evaluate to true as a boolean.

However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent:

$canMerge = ($condition1 && $condition2);

Upvotes: 41

Polsonby
Polsonby

Reputation: 22875

The value of 'false' is true. You need to remove the quotes:

$canMerge = ($condition1 && $condition2) ? true : false;

Upvotes: 1

Related Questions