Ternary Operation

1 min read 216 words

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!

Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags