0

i wonder why i could not find an answer from searching through google? how do you compare if a boolean variable is true or false, i have the ff code: the value of $input['appointed_phases1'] is true while the value for $input['appointed_phases2'] is false:

    $appointed_phases = 0;
    if($input['appointed_phases1'] == true && $input['appointed_phases2'] == true){
        $appointed_phases = 3;
    }elseif($input['appointed_phases1'] == true && $input['appointed_phases2'] == false){
        $appointed_phases = 1;
    }elseif($input['appointed_phases1'] == false && $input['appointed_phases2'] == true){
        $appointed_phases = 2;
    }else{
        $appointed_phases = 0;
    }

for some reason the value of $appointed_phases is always 3

Viscocent
  • 2,024
  • 2
  • 19
  • 26
  • 7
    Show the output of `var_dump($input['appointed_phases1'])` and `var_dump($input['appointed_phases2'])`. I suspect they are strings and not actual boolean values. In which case type juggling will make both comparisons equal to `true` thus making the first condition always trigger. – John Conde Oct 01 '19 at 12:16
  • You can make it much simpler with binary bits. When both `2` and `1` are set, it's `3`, when only `2` is set, it's `2`, when only `1` is set, it's one, else, it's zero. – nice_dev Oct 01 '19 at 12:34
  • When checking for a boolean you need to always use the strict comparison operator `===` not `==`. – Exadra37 Oct 01 '19 at 12:54

1 Answers1

4

I think your $input['appointed_phases1'] contains a string value. In PHP, any string value that is not empty evaluates to true.

See this question: How to convert string to boolean php

You can cast the value of $input['appointed_phases1'] to a boolean, or you can compare this value with 'true' instead of true.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Bensjero
  • 58
  • 6