There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:
Example :
// Normal condition
$name = 'ali';
if($name === 'ali'){
echo "Yes I'm ali";
}else{
echo "No I'm not ali";
}
// output: Yes I'm ali
/* In Ternary condition
---------------------------
Syntax : Condition ? Statement1 : Statement2;
Statement1 : if condition is true ..
statement2 : if condition is false ..
*/
$name = 'ali';
$name === 'ali' ? echo "Yes I'm ali" : echo "No I'm not ali" ;
// output: Yes I'm ali
Generally, Ternary operators are not used with complicated conditions that have multiple conditions (elseif) and it's better to use Normal condition syntax (if elseif else)with complicated conditions.
Example:
$age = 15;
if($age > 18){
echo "You can enter";
}
elseif($age === 18){
echo "You can enter with an adult one only";
}
elseif($age === 13){
echo "You are small";
}
else{
echo "You can't enter";
}
Now if we want to write the same block of code but using the Ternary operator :
Example:
/*
First The answer will be stored in $result variable.
All code at Statement2 will be inside parentheses.
Condition ? Statement1 : (Statement2...) then every condition will be too
inside parentheses like The example down.
*/
$age = 15;
echo $result = $age > 18 ? 'You can enter' : (($age === 18) ? 'You can enter with an adult one only' : (($age === 13) ? "You are small" : "You can't enter")) ;
// Output: You can't enter