PHP Ternary Operator - Conditional Shorthand

I absolutely love the ternary operator and use it throughout my code. Sometimes people call it shorthand conditional. It is a super-simple replacement for a basic if/else operation. Basically there are two possibilities dictated by one conditional as follows:

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Example:

PHP:
  1. $do = (empty($_POST['do'])) ? 'nothing' : $_POST['do'];

Classic Way:

PHP:
  1. if (empty($_POST['action'])) { 
  2. $action = 'default';
  3. }
  4. else {
  5. $action = $_POST['action'];
  6. }

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank

Home | PHP | PHP Ternary Operator - Conditional Shorthand