PHP Ternary Operators (Examples)

​​


Hello dear readers! welcome back to another section of our tutorial on PHP. In this tutorial guide, we will be discussing about the PHP Ternary Operator.

Try the following example below to have a proper understanding of the ternary operator. Copy and paste the following code in a text.php file and save the file in your PHP Server's document root and then browse it using any Web browser.

<html>
   
   <head>
      <title>Ternary Operator</title>
   </head>
   
   <body>
   
      <?php
         $a = 10;
         $b = 20;
         
         /* If condition is true then assign a to result otheriwse b */
         $result = ($a > $b ) ? $a :$b;
         
         echo "TEST1 : Value of result is $result<br/>";
         
         /* If condition is true then assign a to result otheriwse b */
         $result = ($a < $b ) ? $a :$b;
         
         echo "TEST2 : Value of result is $result<br/>";
      ?>
   
   </body>
</html>

Output

When the above code is executed, it will produce the following result -

TEST1 : Value of result is 20
TEST2 : Value of result is 10

RECOMMENDED POST: PHP Assignment Operators

Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about PHP Decision Making.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.