So, I though Iβd start this series called Programming Tip Of The Day to write about useful things I come across in programming. Both to educate my readers and as a personal archive of ideas and tips.
I will kick it off today with a quick rant about the ternary operator. I <3 the ternary operator. Itβs quick, efficient and saves a lot of ugly code.
For those of you who donβt know, the ternary operator is made up of 3 elements: The condition and two results. It is of the form:
This is much nicer than an if statement. So here is a brief example about how a ternary operator can replace an if-statement.
<code class=βcβ>if(isSnowing) { iMustBe = "cold"; } else { iMustBe = "warm"; }</code>
<code class=βcβ>iMustBe = isSnowing ? "cold" : "warm";</code>
That is so much easier to read (IMHO). You can even do clever things in printing. Here is a small example in PHP for using the ternary operator when doing an echo.
<code class=βphpβ><?php echo "I am a ".((height > 72) ? "tall" : "short")." person!"; ?></code>
Most languages support the ternary operator. Check out this wiki page if you want more info.
Happy programming!