PHP Tutorial
Home
PHP Install Xampp
PHP Syntax & Comments
PHP Variables
PHP Constants
PHP Data Types
PHP Echo & Print
PHP Strings
PHP If...Else...Elseif
PHP Ternary Operator
PHP Loops
PHP Functions
PHP Arrays
PHP GET & POST
PHP Advanced
PHP Date and Time
PHP Include and Require
PHP File Upload
PHP Sessions
PHP Cookies
PHP Send Email
PHP JSON Parsing
PHP MySQL Database
PHP MySQL Introduction
PHP Connect to MySQL
PHP MySQL Create DB
PHP MySQL Create Table
PHP MySQL Insert Data
PHP MySQL Select Data
PHP MySQL Delete Data
PHP MySQL Update Data
PHP MySQL Where
Ternary operator provides a short hand way of writing the if else statements block of codebook. It is represente by the question mark symbol (?) and it takes three operands: a condition to check, a result for true, and a result for false.
Syntax :
(Condition) ? (Statement1) : (Statement2);
Condition : Ternary operator is the expression to be evaluated and returns a boolean value.
Statement 1 : It is the statement to be executed if the condition results in a true block.
Statement 2 : It is the statement to be executed if the condition results in a false block.
how this Ternary operator works, consider the below examples :
Example :
<?php $age = 20; if($age < 18){ echo 'Child'; // Display Child if age is less than 18 } else{ echo 'Adult'; // Display Adult if age is greater than or equal to 18 } ?>
Using the PHP ternary operator same code could be written in a more compact way :
Example :
<?php $age = 20; echo ($age < 18) ? 'Child' : 'Adult'; ?>