PHP: The One Line IF Statement

PHPI’m a big fan of doing everything the verbose way when it comes to coding, all my conditional statements are always decked out with the proper tabbing and the full bracketing that they so richly deserve. To me, this makes the code far easier to read and more importantly follow, a fairly important consideration when I think of just how often I have to go back to legacy code and try to figure just what the heck is going on.

But, as will everything in life there are always exceptions, times when you need to break your own rules and get things done quickly, efficiently. So when you don’t have time to fully write out your PHP IF statement, here’s the alternative for you!

The one line, condensed IF statement, known as a ternary operator to those in the business:

$x = ($myvalue == 10) ? "the value is 10" : "the value is not 10";

As you can see in the example above, $x is assigned the result of the conditional check held in the first set of brackets, the results of which are defined by the if and else return values delimited by the : character.

This means that if $myvalue = 10 then the “the value is 10″ line will be assigned to $x, and obviously the other way around for cases where $myvalue != 10.

And there you have it. Shorthand indeed that goes a long way in saving you from typing out all those seemingly unnecessarily verbose brackets! :P

Related link: http://en.wikipedia.org/wiki/%3F:

You might also enjoy:

  • I stumbled across this gem of a quick guide to Bash shell scripting over at some or other forum and so as not to lose this valuable resource for my later us ...
  • If you are in the middle of running your nice and juicy, newly typed up bash script and it throws up its arms with the following error message:[: =: unary o ...
  • I know designing for accessibility is important, but nuts, nothing is more annoying than accidentally enabling Microsofts StickyKey functionality. It gets e ...
  • Some time ago I whipped up a quick mobile interface to Touchwork's M4E system, essentially just a basic portal listing of the event delegates with their ass ...
  • While detecting browser type and then handling it accordingly is not particularly difficult these days, there are times when one simply doesn't feel like re ...

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged , , single line if, ternary. Bookmark the permalink.
    blog comments powered by Disqus