Submit Your Article
Home Articles News Tutorials Videos Add An Article
Topics: Design Photoshop Programming PHP CSS Java Database Web Development Javascript Ajax
– Close + Open

Find Out More About DevWebPro!

Sign up for the newsletter


» Terms & Conditions

Welcome to the New DevWebPro!

DevWebPro Includes:
  Hundreds Of Tutorials   Developer News
  Unique Gadget Videos   Tons of Topics to Discuss
  Expert Advice   We Will Publish Your Articles

PHP 5.3 and The Ternary Shortcut

By: Lamonte
Sunday, August 24th, 2008
Text: Decrease Font Size Increase Font Size | Print Print Article | Share: Delicious Digg StumbleUpon Post to Twitter Post to Facebook
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.

Topics: , ,

About the Author:

Leave a Comment

DevWebPro is an iEntry Network ® publication - © 1998-2010 All Rights Reserved