Page 1 of 1

Ternary conditionals

Posted: 11 Nov 2015 12:18
by armsys
Referring to

Code: Select all

::$r = ("a" == "a"); $r = ($r?"True":"False"); msg $r;
,
how to interpret ($r?"true":"False")?
Is the "?" (question mark) an implied "if"? :oops:

Ternary conditionals

Posted: 11 Nov 2015 12:45
by highend
It's a ternary conditional.

Advanced Topcis - Scripting - Ternary Conditionals

Code: Select all

$r = ("a" == "a");
$r = 1

Code: Select all

$r = ($r?"True":"False");
Because $r = 1 (which is also a boolean "true") -> $r = "True"

It's just a short form of an if / else statement.

Re: Ternary conditionals

Posted: 11 Nov 2015 12:59
by armsys
highend wrote:It's a ternary conditional.
Yes, I found it in the manual. I should have read ahead to locate the description on the weird construct (condition)? value-if-true : value-if-false.
Thank you for your fast help.

Re: Ternary conditionals

Posted: 11 Nov 2015 16:25
by bdeshi
in my opinion, it's a good idea to enclose the whole thing in another set of braces: ( (condition) ? ReturnIfTrue : ReturnIfFalse )

Re: Ternary conditionals

Posted: 11 Nov 2015 22:54
by armsys
SammaySarkar wrote:in my opinion, it's a good idea to enclose the whole thing in another set of braces: ( (condition) ? ReturnIfTrue : ReturnIfFalse )
Thank you for your reminder. Agree. I'll follow your scripting style because it helps improve readability.

Re: Ternary conditionals

Posted: 15 Sep 2016 11:15
by autocart
1) is it safe to use expressions in the if-true and if-false parts of the ternary conditional?
2) is it safe to nest ternary conditionals? e.g.: $coolVar = $groofyVar?groofyVar:isset($coolVar)?$coolVar:""; $coolVar = $groovyVar?groovyVar:isset($coolVar)?$coolVar:"";

Re: Ternary conditionals

Posted: 15 Sep 2016 11:45
by admin
I'd think so. But the parsing can get tricky depending on what you do. Make a test...

ADD:
Parentheses help. This seems to work. Play with it...

Code: Select all

// nested ternaries
  //$coolVar = "cool";
  //$groofyVar = "groof";
  echo (isset($groofyVar)?$groofyVar:(isset($coolVar)?$coolVar:"NO"));

Re: Ternary conditionals

Posted: 15 Sep 2016 12:10
by bdeshi
It's perfectly okay to nest ternary conditionals or expressions within another ternary. You can also have ternaries in expressions. As I commented earlier here, when in doubt, enclose in braces.

Re: Ternary conditionals

Posted: 15 Sep 2016 12:15
by autocart
just realized that groovy is spelled with a "v". (I think I was connecting it to goofy in my mind at first.)
sorry for misleading u, Don, I am also not a native English speaker.

Thx for all help.

Re: Ternary conditionals

Posted: 15 Sep 2016 12:26
by admin
Luckily I coded it so that mispelled variables also work! :titter: