PHP Ternary Operator

In this chapter you will learn:

  1. What is Ternary Operator
  2. Syntax for PHP Ternary Operator
  3. Note for PHP Ternary Operator
  4. Example - Convert between ternary operator and if statement

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/*from   ja v  a 2  s  .  c om*/
$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/*from   ja  v  a  2 s  .c o  m*/
      $age = 10;
      if ($age < 16) { 
             $agestr = 'child'; 
      } else { 
             $agestr = 'adult'; 
      } 
?>

Next chapter...

What you will learn in the next chapter:

  1. What are bitwise operators
  2. What are PHP Bitwise Operators
  3. Example - bit calculation
Home » PHP Tutorial » PHP Operators
PHP Assignment Operators
PHP Arithmetic Operators
PHP Incrementing and Decrementing Operators
PHP Comparison Operators
PHP Logical Operators
PHP String Operators
PHP Ternary Operator
PHP Bitwise Operators
PHP Execution Operator
PHP Operator Precedence