PHP Tip: Tertiary Operator
February 23rd, 2008 by John Hok
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:
<?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:
<?php
echo (5 > 10) ? ‘The world is ending.’ : ‘Yes, I am still sane!’;
?>
What it basically does is
(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!):
(($query_count_result[‘count’] > 1) ? (($query_count_result[‘count’] == 1) ? $query_count_result[‘count’].‘ Song’ : $query_count_result[‘count’].‘ Songs’) : ‘No Songs’)
