The Ternary operator in PHP is a built-in operator that acts like an if statement in PHP. It shares with several other languages.

It has an unusual form, here it is:

Syntax:  $result = condition ? expression1 : expression2;

Okay, what’s that…? What’s going on here? IF condition is true, the ternary operator—which is made up of characters ?:—returns expression1. Otherwise, it returns expression2. So as we can see this is an operator that lets us make real-time choices. Let’s take an example. This code displays “its raining outside.” If the raining variable is true, and “I’m sleeping inside.” Otherwise:

<?php
   
    $raining=TRUE;
   
    if($raining==TRUE)
    {
         echo “Its raining outside.”;
    }
    else
    {
         echo “I’m sleeping inside.”;
    }
?>

 

Here’s the same code using the ternary operator—note down how compact this is:

<?php
    $raining=TRUE;
    echo ($raining==TRUE) ? “its raining outside.” : “I’m sleeping inside.”;
?>

 

That’s it. Pretty cool huh!

If you have any issue, let us know in the comment box.