PHP Ternary Operator

Description

The ternary operator is a shorthand for if statements.

Syntax

PHP ternary operator has following syntax.

expression = ( expression1 ) ? expression2 : expression3;

Note

The ternary operator takes three operands:

  • a condition (expression1),
  • a result(expression2) for true, and
  • a result(expression3) for false.

The preceding code reads as follows:


If expression1 evaluates to  true, 
  the overall expression equals  expression2 ;  
otherwise, 
  the overall expression equals  expression3 .  

Example


<?PHP//  w  w  w  .  java2 s. c o m
$age = 10;
$agestr = ($age < 16) ? 'child' : 'adult'; 
print $agestr;
?>

The code above generates the following result.

That ternary statement can be expressed in a normal if statement like this:


<?PHP//www.  jav  a 2 s  .com
      $age = 10;
      if ($age < 16) { 
             $agestr = 'child'; 
      } else { 
             $agestr = 'adult'; 
      } 
?>




















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition