Ternary Operator – Your Best Friend

If you have never used the Ternary Operator, or ? operator, your life is about to change. The ternary operator is used as a shorthand for if .. else structures that can really clean up your code. Some may want to classify this under a intermediate or advanced skill, but it is so useful that I think it should be included with the most basic tutorials.

Take this for example:

if( $use_live_server ) {
     $url = "http://www.thelivesite.com"
} else {
     $url = "http://www.thedevsite.com";

This block of code sets which URL we want to connect to based on if a variable called $use_live_server. While the block of code is perfectly valid, there is a much better way to do the exact same thing in a single line of code.

$url = $use_live_server ? "http://www.thelivesite.com" : "http://www.thedevsite.com";

That one line of code does the exact same thing and once you understand how this works. Here is how the ternary operator works:

$variable = $expression_to_evaulate ? true : false

You do not necessarily have to have a variable that is true or false. You can do any expression you need to.

Leave a Reply

Your email address will not be published. Required fields are marked *