Ternary If Else

5 posts Page 1 of 1
Contributors
User avatar
XTechVB
VIP - Site Partner
VIP - Site Partner
Posts: 727
Joined: Thu May 20, 2010 10:32 am

Ternary If Else
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.
Last edited by XTechVB on Wed Feb 19, 2014 5:48 pm, edited 4 times in total.
You can find me on Facebook or on Skype mihai_92b
User avatar
AnoPem
VIP - Donator
VIP - Donator
Posts: 441
Joined: Sat Jul 24, 2010 10:55 pm

Re: Ternary If Else
AnoPem
Very useful thanks :D
https://t.me/pump_upp
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

Re: Ternary If Else
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"; }
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
User avatar
XTechVB
VIP - Site Partner
VIP - Site Partner
Posts: 727
Joined: Thu May 20, 2010 10:32 am

Re: Ternary If Else
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 .
You can find me on Facebook or on Skype mihai_92b
User avatar
rocky4126
VIP - Donator
VIP - Donator
Posts: 258
Joined: Mon Nov 16, 2009 7:39 pm

Re: Ternary If Else
rocky4126
XTechVB wrote:
True but i prefer Ternary when i need to check something inline, plus is shorter :D .
And looks neater, of course.
Image
5 posts Page 1 of 1
Return to “Tutorials”