The term ternary operator comes from the fact that the operator requires three operand
expression, value1, value2
Introduction To Ternary Operator
Ternary operator is a shorthand form for writing the
if...else
Rather than writing
<?php
if (condition) {
$result = value1;
} else {
$result = value2;
}
You get to write
$result = condition ? value1 : value2;
How does Ternary Operator Work??
1) The condition is tested, if true value1
is returned while value2
is returned when it is false
2) The result of the expression is assigned to $result
Using Ternary Operator allows you to write cleaner code.
Example:-
In this example, if the value of $a is greater than 15, then 20 will be returned and will be assigned to $b, else 5 will be returned and assigned to $b.
<?php
$a = 10;
$b = $a > 15 ? 20 : 5;
print ("Value of b is " . $b);
?>
Output:-
Value of b is 5
Why Use Ternary Operators ??
We use Ternary Operators when we need to simplify the if else statement that is assigning values based on a condition. We also use it to improve readability and simplify the code.
Example:-
if(isset($_POST['Name']))
$name = $_POST['Name'];
else
$name = null;
if(isset($_POST['Age']))
$age = $_POST['Age'];
else
$age = null;
?>
You can use the ternary operator to rewrite it as
<?php
$name = isset($_POST['Name'])?$_POST['Name']:null;
$age = isset($_POST['Age'])?$_POST['Age']:null;
?>
Giving you a cleaner code.