PHP 5.3 and The Ternary Shortcut

Learning PHP 5
Learning PHP 5

As you all might know PHP 5.3 alpha 1 was released not to long ago and people are still wondering what this “Ternary Shortcut” is all about.  In this article you will understand its basic usage in a real application.

So how does it work?

Basically the new ternary shortcut is used as a true or false statement.  Back with the old ternary statement, it took 4 sections which:

  1. Assigned to a variable (When we assign the ternary to a variable)
  2. Did a “IF” statement
  3. Return Clause 1 (Which if the “IF” statement is true return this value else return clause 2)
  4. Return Clause 2
Looks Like: $var = ( expression ) ? (clause 1) : (clause 2);

The Ternary looks like it doesn’t work like that, it takes 3 sections:

  1. Assigned to a variable
  2. Do a “IF” statement” (Return 1 else return clause 2)
  3. Return Clause 2
Looks Like: $var = ( expression/clause 1) ?: (clause 2);

When would I use it?

This question came up to me a few times from a few friends and they asked, when would I use this.  Well the best place to use this in your scripts are for options that contains checkboxes.

Why Check Boxes?

Well as I stated above, The Shortcut Ternary feature is basically a yes or no (or on or off) feature, and usually checkboxes are used for “on” and “off” features.  We could use a ternary statement like the following:

$website_offline = isset($_POST['website_offline']) ?: 0;

Basically what I did there was if the input checkbox was set then it would return 1 else if it wasn’t set it would return 0.

I hope this clears up things with future developers.  If you would like to elarborate on this article please feel free to comment.

Leave a comment