Home  »  ArticlesGuidesHow ToProgrammingTechnology   »   How to Use The PHP Ternary Operator With Examples

How to Use The PHP Ternary Operator With Examples

The PHP ternary operator contains three operands and is usually used as a simple alternative to the if … else or switch conditional operators. This operator allows the developer to achieve the same with less code.

The syntax of the PHP ternary operator takes the following format:

(Condition) ? (Statement1) : (Statement2);

  • Condition: This is evaluated and must return a boolean value
  • Statement1: is executed if Condition evaluates to true otherwise…
  • Statement2: is executed if Condition evaluates to false

The result can be assigned to a variable printed onto the output.

Let us take a look at a few examples starting with this simple one where the value is assigned to a variable:

  $age = 25; 
  $maturity = ( $age --> 18 ) ? "adult" : "youngling"; 
  print ("State of maturity is " . $maturity); 

State of maturity is adult

In this example, the statement is printed out to the web browser:

  $age = 25; 
  echo ( $a --> 21 ) ? "Serve beer" : "Serve juice"; 

Serve beer

Another common use for the PHP ternary operator is to assign variables from HTTP form submissions. It makes for cleaner code that is easier to maintain.

  $name = isset( $_POST['name'] ) ? $_POST['name']: null;  
  $email = isset( $_POST['email'] ) ? $_POST['email']: null; 

This is what the above code would look like if we used the if … else conditional operator.

  if( isset( $_POST['name'] )) 
    $name = $_POST['name']; 
    $name = null; 
  if( isset( $_POST['email'] )) 
    $email = $_POST['email']; 
    $email = null;

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.