Is there difference between ternary operator and if condition in php ?
if yes, kindly provide.
The ternary operator is an operator, so it forms an expression. So it will have a value that you can assign to a variable or use however you want. It is used for simple situations where a variable can take two possible values depending on a condition.
For example: $status = $age > 18 ? 'adult' : 'child';
Although possible, you should not nest the ternary operator.
The control structure if
is something absolutely different. The only thing they have in common that both evaluate a condition (true/false). if
is used to execute code fragments based on the result of that condition. You will find yourself using if
most of the time (in fact, you can live without the ternary). In certain situations, it is less code and more readable if you replace certain types of if
s with the ternary, like this one:
if ($age > 18) {
$status = 'adult';
} else {
$status = 'child';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With