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?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.
If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).
Ternary Operator in C takes three arguments: The first argument in the Ternary Operator in C is the comparison condition. The second argument in the Ternary Operator in C is the result if the condition is true. The third argument in the Ternary Operator in C is the result if the condition is false.
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);
The value of 'false' is true. You need to remove the quotes:
$canMerge = ($condition1 && $condition2) ? true : false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With