PHP: Ternary Operators.

This is a tutorial on how to use the ternary operator in PHP. In this guide, I will explain what ternary operators are and how to use them. Furthermore, I will explain when to use them.

A ternary operator is a conditional expression that allows you to create inline IF statements.

To put that in more simple terms: It is basically a shorthand IF / ELSE statement.

By using this “shortcut”, you can turn three or four lines of code into one. As a result, it can make your code look cleaner and more readable.

How to use the Ternary Operator in PHP.

The syntax of a ternary IF statement in PHP looks like this:

(Condition) ? (Do this if condition is TRUE) : (Do this if condition is FALSE)

Take the following piece of code as an example:

//Basic ternary
echo (2 > 1) ? 'True!' : 'False!';

In the PHP snippet above, we have the following:

  • Before the question mark symbol, we have the condition. In this case, the condition is: “IF 2 is bigger than 1”.
  • After the question mark symbol, we have the code that will execute if the condition is TRUE.
  • Then, at the end, after the colon character, we have the code that will execute if the condition is FALSE.

The PHP snippet above is always going to echo out the string “True!” This is because 2 will always be larger than 1.

Let’s take a look at one more example, in which we assign a GET parameter to a PHP variable if it exists:

//Attempt to GET the id parameter.
$id = (isset($_GET['id'])) ? $_GET['id'] : false;

In this case, our ternary operator will only assign the GET parameter “id” to our variable $id if it exists. Otherwise, it will assign a FALSE value. Our code can be broken down as follows:

(IF the GET parameter “id” is set) ? Assign $_GET[‘id’] to $id : Otherwise, assign FALSE to $id

This is a common approach to retrieving URL parameters in PHP. This is because referencing a GET variable that does not exist will cause an undefined index warning.

When should I use ternary operators?

You should use ternary operators if the conditional statement is simple enough and the shorthand version is more readable.

Take a look at the following PHP code, which contains a simple IF / ELSE statement:

//IF the POST variable name is set.
    //Print it out.
    echo htmlentities($_POST['user']);
} else{
    echo 'No name provided.';

As you can see, the IF statement above is very basic. So basic, in fact, that we could easily convert those four lines of code into an inline IF by using the ternary operator:

//An example of a ternary operator being used.
echo (isset($_POST['name'])) ? htmlentities($_POST['user']) : 'No name provided.';

In the PHP above, we shortened our original IF statement by using the ternary operator.

This “Ternary IF” basically acts like a shorthand IF statement. It allows you to write basic IF / ELSE statements in one line of code.

Let’s take a look at another example:

//Temperature in degrees celcius
$tempCelcius = 3;

//If it is 0 or below
if($tempCelcius <= 0){
    $freezingPoint = true;
} else{
    $freezingPoint = false;

Here, you can see that our code only contains one operation per statement. All we are essentially doing is assigning a TRUE or FALSE value to a variable. As a result, this can definitely be shortened:

$tempCelcius = 3;
$freezingPoint = ($tempCelcius <= 0) ? true: false;

Much more concise. And it’s readable too!

Ternary operators can also help you to avoid printing out HTML with PHP:

    <?php foreach($animals as $animal): ?>
        <li class="<?= ($animal == 'Dog') ? 'dog' : 'animal' ?>">
            <?= $animal; ?>
    <?php endforeach; ?>

In the snippet above, we used a ternary operator to print out the class name for a HTML list element.

When NOT to use ternary operators.

You should not use a ternary operator if it makes your code less readable.

Take a look at the following example:

$tempCelcius = 3;

if($tempCelcius <= 0){
    $freezingPoint = true;
    $database->update('temperature', 'freezing', 1);
} else{
    $freezingPoint = false;
    $database->update('temperature', 'freezing', 0);

Here, you can see that our IF / ELSE statement is a little more complex. Instead of having one operation per statement, it has two.

As a result, you will not be able to convert this into a shorthand IF. Attempting to do so will most likely result in a parse error. Even if you did find some sort of “trick” to get around this, it would only make the code less readable.

This is especially true for IF statements with multiple conditions:

    $i > 0 && 
    in_array($var, $arr) && 
    ($j > 0 || $t < 10) && 
   //Do something 

Turning the above code into a shorthand IF statement would be silly. Instead of making your code more readable, all you’d be doing is creating lengthy lines of PHP code. And that defeats the purpose.

echo ($i > 0 && in_array($var, $arr) && ($j > 0 || $t < 10) && isset($_GET['id'])) ? 'TRUE' : 'FALSE';

This code is nasty because a lot of IDEs will force you to scroll across in order to view it. And trust me, that can be frustrating.

Remember: If it’s not simple, leave it as it is. Otherwise, you’re just creating messy code that will be a pain to edit at a later stage.

Hopefully, you found this guide useful!