PHP Ternary Operator – Conditional Shorthand

Like this blog? Consider exploring one of our sponsored banner ads...

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']; 
}

About this entry