Page 1 of 1

Ternary If Else

Posted: Wed Feb 19, 2014 4:44 pm
by XTechVB
A Ternary if else is basically a normal if else statement but which you can also use inline.
For example, when you write an if else statement you do it like this:
Code: Select all
if(1 + 1 == 2) {
	echo "yes";
}
else {
	echo "no";
}
Now what happens if you want to write that whole thing in a single line? Well you use it's ternary equivalent, like this:
Code: Select all
echo (1 + 1 == 2) ? "yes" : "no";
The ternary if else statements work just like the normal ones condition > action if true > action if false only they use this syntax:
Code: Select all
Condition ?(if true) do action :(else) do other action
Also they must always be comprised of both (if) and (else) elements and they don't support elseif.

Well that's it for today :D i hope you find this tutorial easy to learn and useful.

Re: Ternary If Else

Posted: Wed Feb 19, 2014 5:20 pm
by AnoPem
Very useful thanks :D

Re: Ternary If Else

Posted: Wed Feb 19, 2014 10:48 pm
by smashapps
Interesting I didn't know that.

However you still can do this:
Code: Select all
if(1 + 1 == 2) { echo "yes"; } else { echo "no"; }

Re: Ternary If Else

Posted: Wed Feb 19, 2014 11:45 pm
by XTechVB
smashapps wrote:
Interesting I didn't know that.

However you still can do this:
Code: Select all
if(1 + 1 == 2) { echo "yes"; } else { echo "no"; }
True but i prefer Ternary when i need to check something inline, plus is shorter :D .

Re: Ternary If Else

Posted: Wed Aug 13, 2014 3:56 pm
by rocky4126
XTechVB wrote:
True but i prefer Ternary when i need to check something inline, plus is shorter :D .
And looks neater, of course.