February 23rd, 2008
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')
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!
I love coding like that.
What I also figured out a few months back was that you could nest functions inside arrays.
I try not to use it because I cannot find it documented anywhere, basically if it changed then I would only have myself to blame, but try this…
$arr = array(’function1′ => function1());
I’m using tertiary operators for javascript too and it’s awesome :D
Hmm I have never actually done that before but it makes total sense and I don’t think it would break since it works on the fundamental principles of variable assignments.
Each index in the array would point to a variable.
It’s the same as assigning a variable a function like $function = function1();
Neat though, I’m trying to think where this would be useful in my past coding…
Never use Tertiary Operator, its to slow.
einand@jagge ~/programmering/switch $ php test.php
if:50
Tertiary:64
This is value calculated on one question looped 300000000 times.
(($query_count_result[‘count’] >= 1) ? (($query_count_result[‘count’] == 1) ? $query_count_result[‘count’].‘ Song’ : $query_count_result[‘count’].‘ Songs’) : ‘No Songs’)
now it reports 1 song
My take on simplifying the code… :)
$count = $query_count_result['count'];
echo ((!empty($count)) ? (($count == 1) ? $count.’Song’ : $count.’Songs’) : ‘No Songs’)
I didn’t test it, but it should work…