What is a ternary operator in PHP?
Overview
At times we may want to add some conditional statements in our HTML codes and maintain the indentation or neatness of the code blocks. The best way to add simple conditional statements neatly inside our HTML code block is by using ternary operators. The conditional ternary operator assigns a value to a variable based on some condition. It is used in the place of the if statement.
Why use ternary operators?
Ternary operators allow shortened codes, are simple to understand, and are easy to read.
Syntax
condition ? value if true : value if false
- The
conditionis the code/expression whose output defines the value that is used.
- The value after the
?is returned if the condition returnstrue.
- The value after the
:is returned if the condition returnsfalse.
Example
<?php$score = 43;$final = ($score > 30) ? 'Win' : 'Lost';echo $final;
Code explanation
Line 3: We check to see that the $score is greater than 30, which is true. Therefore, echo $final; prints Win.