-5

what does $mark_state_id = $r['mark_state_id'] == 2 ? 1 : 2; mean ?

Friends, what is it doing above?

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
legolas
  • 725
  • 1
  • 5
  • 7
  • `$mark_state_id` becomes 2 unless `$r['mark_state_id']` is 2, in which case it becomes 1. – Ja͢ck Jun 15 '15 at 06:44
  • Seems like a toggle statement, though, so `$mark_state_id = 3 - $r['mark_state_id'];` should also work ;-) – Ja͢ck Jun 15 '15 at 06:46

3 Answers3

1

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.

Drakes
  • 23,254
  • 3
  • 51
  • 94
0

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;
}
Daan
  • 12,099
  • 6
  • 34
  • 51
0

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;
}

Ternary Operator

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.

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87