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.
Ternary operators allow shortened codes, are simple to understand, and are easy to read.
condition ? value if true : value if false
condition
is the code/expression whose output defines the value that is used.?
is returned if the condition returns true
.:
is returned if the condition returns false
.<?php$score = 43;$final = ($score > 30) ? 'Win' : 'Lost';echo $final;
Line 3: We check to see that the $score
is greater than 30
, which is true
. Therefore, echo $final;
prints Win
.