Subscribe to...
Posts
Comments

PHP Tip: Tertiary Operator

This is just a quick PHP tip I’d like to share. It’s called the Tertiary Operator. It’s basically a way to simplify simple(and complex) if statements into one liners!

Say for example you have a conditional statement like:

Code (php)

<?php
if (5 > 10)
{
        echo ‘The world is ending.’;
}
else
{
        echo ‘Yes, I am still sane!’;
}
?>

You can reduce this statement into the following using tertiary operators:

Code (php)

<?php
echo (5 > 10) ? ‘The world is ending.’ : ‘Yes, I am still sane!’;
?>

What it basically does is

Code (php)

(if this statement is true) ? (we should do this to it) : (else goes here in an if statement)

This can come in real use when you don’t want to stick in an if statement in the middle of an echo statement for example. You can even nest them! Here is a more complex one I used in one of my scripts(sorry about the code wrapping!):

Code (php)

(($query_count_result[‘count’] > 1) ? (($query_count_result[‘count’] == 1) ? $query_count_result[‘count’].‘ Song’ : $query_count_result[‘count’].‘ Songs’) : ‘No Songs’)

Can you figure out what that statement is doing? I might be able to actually simplify this statement but I didn’t really give it much thought at the time of making it. I just wanted to get it to work and wasn’t really thinking about what was the most optimal way to do it. Hope this tip was useful!

Related posts

Stumble it!Save to del.icio.usSubmit to Digg

Leave a Reply