The ternary operator is a shorthand structure which assigns different values to a variable depending on condition is true or false.
Ternary operator consists of (?:)
1 |
$var = (condition) ? value if true : value if false; |
This is equivalent to normal if else condition:
1 2 3 4 5 |
if($condition is true){ $var = 'This'; }else{ $var = 'Something else'; } |
Example
1 2 3 |
$age = 27; $result = ($age == 27) ? "Yes you guessed it right" : "Keep trying"; echo $result; |
Use ternary operator to tell value is true or false. It is easy to write and saves you from writing a lot of code then an conditional if else statement.