PHP: The One Line IF Statement CodeUnit 06 APR 2009

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:

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.