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!
We can nest ternary operators to test multiple conditions.
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.
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.
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.
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.
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 )
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