Ternary Operators

Ternary Operator

You probably already know how to write if-then statements in PHP and Ruby.

<?php // a simple PHP example
  if (condition) {
    statement1;
  } else {
    statement2;
  }
?>

But have you discovered the usefulness of ternary operators yet?

Don’t let the fancy term fool you—”ternary” just means that it takes three arguments. You will notice that the if-then statment above, as in Ruby, takes three arguments: condition, statement1, statement2. Ternary operators are the shorthand way to achieve the same results. This particular shorthand format was popularized in C, and, while the documentation can be hard to find, ternary operators are available both in PHP and Ruby.

1
<?php condition ? statement1 : statement2; ?>
1
<% condition ? statement1 : statement2 %>

It works just like an if-then statement. If the argument (or condition) before the ? is true, the argument preceeding the : is returned, otherwise the argument following the : is returned. If you’re if-then statement is very simple, it’s a much more concise way to write it. It takes up less room on the page, and makes your code easier to read. It doesn’t work as well when your if-then statement is complicated or longer than one line of code. I find it is also helpful for variable assignment or simple output.

Here are some fictional examples in Ruby on Rails:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%  # using it for variable assignment
  @logged_in = has_cookie_already(@user) || has_session(@user) ? true : false
%>

<% # using it for variable assignment another way
  @user.access_level > 5  ? (pg_prefs = @user.prefs) : (pg_prefs = @default_prefs)
%>

<% # using it to call methods
  (@page_count && @page_count > 1) ? find_all_pages(@page_count) : find_page()
%>

<% # using it for output %>
Welcome, <%= @logged_in ? @user.first_name : 'Guest' %>.

In PHP, it’s the same thing—just be aware that the ternary operator returns a value, but it doesn’t automatically echo the value, so you’ll need to add your own if you want the value to output.

You can daisy-chain ternary operators too, but be careful or they will start to become less readable fast. And once you have a confusing, multi-line statement, you are better off using the traditional if-then statement. Our coding goals should speed, conciseness and clarity. Let ternary operators help you with that when they can.

One Response to “Ternary Operators”

  1. zDenis Says:

    Just a little note from a very beginner: in ruby the spaces before and after the ? and : are more than important!

Leave a Reply