Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in the ternary operator safe?

I have seen advice that says the ternary operator must not be nested.

I have tested the code below and it works okay. My question is, I haven't seen the ternary operator used like this before. So, is this as reliable as it were used in an if or could something like this come and bite me later(not in terms or readability, but by failing).

$rule1 = true;
$rule2 = false;
$rule3 = true;

$res = (($rule1 == true) && ($rule2 == false) && ($rule3 == true)) ? true : false;

if($res) {
    echo "good";        
} else {
    echo "fail";
}

Thanks!

like image 709
DMin Avatar asked Sep 02 '11 17:09

DMin


People also ask

Can a ternary operator have multiple conditions?

We can nest ternary operators to test multiple conditions.

How do you handle 3 conditions in a ternary operator?

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.

How can use ternary operator for 3 conditions in C#?

Example 1: C# Ternary Operator Since, 2 is even, the expression ( number % 2 == 0 ) returns true . We can also use ternary operator to return numbers, strings and characters. Instead of storing the return value in variable isEven , we can directly print the value returned by ternary operator as, Console.

Which operator is used to check multiple conditions?

Test Multiple Conditions With the || Operator There are times you'll want to perform an action if either of the two possible conditions is true. In this video, you'll use the logical OR (|| ) operator to test multiple conditions.


2 Answers

If the results you are returning from the ternary operator are only "true" and "false", then you don't even need the operator. You can just have:

$res = (($rule1 === true) && ($rule2 === false) && ($rule3 === true))

But, to answer your question, yes multiple conditions work perfectly well.

like image 173
Coeus Avatar answered Sep 20 '22 13:09

Coeus


It's totally legal, it works and is "as reliable as if", but it looks ugly.

If you put each ternary statement inside parenthesis, nesting would be fine too:

$res = ( $rule1 ? true : ( $rule2 ? true : false ) )

The only thing that is advised against in the manual is nesting without parenthesis like this:

$res = ( $rule1 ? true : $rule2 ? true : false )
like image 28
nobody Avatar answered Sep 18 '22 13:09

nobody