what does $mark_state_id = $r['mark_state_id'] == 2 ? 1 : 2;
mean ?
Friends, what is it doing above?
what does $mark_state_id = $r['mark_state_id'] == 2 ? 1 : 2;
mean ?
Friends, what is it doing above?
It is better written as (with brackets for clarity):
$mark_state_id = ($r['mark_state_id'] == 2 ? 1 : 2);
which means "If $r['mark_state_id']
is equal to 2, then return 1, else return 2. Then $mark_state_id
will take the returned value above. This is equivalent to:
$mark_state_id;
if($r['mark_state_id'] == 2){
$mark_state_id = 1;
} else {
$mark_state_id = 2;
}
It uses the ternary operator as a shorthand for if/else.
That is a ternary operator, what is says is: if $r['mark_state_id']
= 2 then $mark_state_id
= 1 else $mark_state_id
= 2.
Which basically means this if/else statement:
if($r['mark_state_id'] == 2){
$mark_state_id = 1;
} else {
$mark_state_id = 2;
}
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
It will check $r['mark_state_id'] == 2
. If it is true
then it will assign 1
else 2
.
$mark_state_id = $r['mark_state_id'] == 2 ? 1 : 2;
similar to -
if($r['mark_state_id'] == 2) {
$mark_state_id = 1;
} else {
$mark_state_id = 2;
}
The ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.