Tuesday, February 14, 2012

Ternary Syntax in PHP


Conditional statements are the building blocks of any complex application, on the web or otherwise.
One of my only objections to the classic 'if' statement is that it can take up several lines even for a simple bit of logic. Of course, there is a solution to this and in this case it's called ternary syntax or a ternary operator.

Ternary means 'composed of three' or 'involving three variables', and so does our classic if statement. The first element is the condition to be evaluated between the parenthesis, the second and third being the 'if' and 'else' statements.

Consider this typical use of an if / else statement:
$val = 5;
if ($val < 10) {                 // first component
    $test = "less than ten!";    // second component
} else {
    $test = "more than ten!";    // third component
}
print $test;

// Output: "less than ten!"

And now the same thing, this time using ternary syntax:
$val = 5;
$test = ($val < 10) ? "less than ten!" : "more than ten!";
print $test;

// Output: "less than ten!"

Here in pseudo-code:
(comparison) ? "if true outcome" : "else outcome";

The above line will return one of the two defined values on the right side, depending on the outcome of the conditional comparison between the parenthesis. A variable is most commonly used to capture the return value, but you can also execute code.
$val = 5;
($val < 10) ? print "less than ten!" : print "more than ten!";

Example Use Cases:

I often use this syntax when checking on an unreliable variable to provide an alternative if the variable isn't set:
$user = ($data->username != "") ? $data->username : "Guest";
print "Welcome, ".$user;
The output will now depend on if a valid ( != "" ) username exists in $data. If the username is blank, the user will instead be referred to as 'Guest'. This outcome is favorable to an error message which is not only ugly but may also reveal the inner workings of your code, which could be a security risk.

Another handy use case is converting and applying unit labels to values. In the example below we take a $value in inches and output it in a more user-friendly format. Values less than one foot are simply concatenated with ' inches', while values over 12 inches are converted to, "x feet, x inches."
$inches = 45;
$converted = ($inches <= 12) ? $inches." inches" : intval($inches/12)." feet, ".($inches % 12)." inches";
print $converted;

// Output: 3 feet, 9 inches
This is a good time to point out that putting this much logic into this syntax gets difficult to look at. When writing complex logic or working on code with others, you may want to avoid going ternary.  A good exercise is writing your if/else blocks with traditional syntax and seeing if you can convert them to ternary syntax.

You can even nest ternary conditionals inside of others, but that's starting to get into syntax so ugly I don't want to talk about it here. Enjoy the new syntax and stay tuned for an upcoming, related post on 'Control Structure Syntax'.

No comments:

Post a Comment