Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there difference between ternary operator and if condition?

Is there difference between ternary operator and if condition in php ?

if yes, kindly provide.

like image 290
mymotherland Avatar asked Dec 09 '22 08:12

mymotherland


1 Answers

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 ifs with the ternary, like this one:

if ($age > 18) {
    $status = 'adult';
} else {
    $status = 'child';
}
like image 62
kapa Avatar answered Dec 11 '22 23:12

kapa