Ternary Operation

If you do not know what the Ternary operator is, or do not use it while you are coding, let me be the first to tell you how much you are missing out!

The Ternary operator looks like this: “?”, that’s right, it’s a question mark!

My favourite way of using it is to shorten Conditional If Statements, so let me show you what I’m on about.

The long way:
<br /> if ($someVariable==true) {<br /> $someOtherVariable=1;<br /> } else {<br /> $someOtherVariable=2;<br /> }<br />

The slightly shorter way:
<br /> if ($someVariable==true) $someOtherVariable=1;<br /> else $someOtherVariable=2;<br />

The Ternary Operation way:
<br /> $someOtherVariable = ($someVariable) ? 1 : 2;<br />

So this is how it works:
<br /> $result = ($condition) ? $ifTrue : $ifFalse;<br />

This can also be used while outputting a string on runtime, I will show this using some javascript:
<br /> function aFunction(arg1,arg2) {<br /> this.arg1 = arg1;<br /> this.arg2 = arg2;<br /> }<br /> function printIt() { with (this) document.write(arg1+' > arg2 '+(arg2?'isTrue':'isFalse')+' arg2'); }<br /> something=new aFunction('FooBar',true);<br /> something.printIt();<br />

If you did not know this or were not sure how it worked, then I’m sure you will now start using it in your code, it really does save time and it looks quite snazzy too!