Feed on
Posts
Comments

PHP, like most programming or scripting language allows for comparison operations bu using if/else. It’s a staple of any good language yet at the same time you can end up writing a lot of code in order to accomplish something very simple. Take for example this simple comparison:

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

All we’re doing here is assigning one value to $action if the form variable action isn’t empty, and different variable if it is. This took up eight lines of code (OK, so you could argue that you could lower that by moving braces around but the code gets ugly fast). How can we clean this up? Enter ternary operators!
What’s a ternary operator you ask? In a nutshell, a ternary operator takes three elements and combines them into one. The basic syntax is (expression 1) ? (expression 2) : (expression 3); which means do expression 2 if expression 1 is true, otherwise do expression 3. It’s just an if/else condition rewritten in one simple line. Taking our previous example, we could consolidate it to this:

$action = (empty($_POST['action'])) ? 'default':$_POST['action'];

Voila! The exact same results in one easy to understand line. I am a huge fan of this shortcut and it comes in very handy when you have basic if/else conditions to check.

2 Responses to “Ternary Operators (or How to Streamline an If/Else Statement)”

  1. Naveen says:

    Since PHP 5.3, we can leave out the middle part (between ? and :) of the ternary operator.
    Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

  2. Naveen says:

    The smiley should be read as : ) in previous post.

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>