Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
Polsonby Avatar asked Aug 05 '08 00:08

Polsonby


People also ask

How do you use ternary expressions?

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.

Why we should not use ternary operator?

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.

Is ternary better than if else?

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).

What are the three arguments of a ternary operator?

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.


2 Answers

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); 
like image 132
Rudd Zwolinski Avatar answered Oct 14 '22 06:10

Rudd Zwolinski


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

$canMerge = ($condition1 && $condition2) ? true : false; 
like image 23
Polsonby Avatar answered Oct 14 '22 08:10

Polsonby