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:

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

Classic Way:

if (empty($_POST['action'])) { 
$action = 'default';
}
else {
$action = $_POST['action'];
}

  • Digg
  • TwitThis
  • del.icio.us
  • Netvouz
  • description
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank
  • Technorati
  • Facebook
  • Google
  • LinkedIn
  • Live
  • MySpace
  • Ping.fm
  • Yahoo! Buzz
  • E-mail this story to a friend!



Home | PHP | PHP Ternary Operator – Conditional Shorthand