PHP Ternary Operator
In this chapter you will learn:
- What is Ternary Operator
- Syntax for PHP Ternary Operator
- Note for PHP Ternary Operator
- 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: