0

I want to store a certain value during a switch/case in PHP, but I don't see what is wrong with this code:

<?php
$weegfactor=67;
$lus=12;

    if($weegfactor<70):
        switch($lus){
        case(1 || 7):
        $verdeling="AAABCD";
        break;
        case(2 || 8):
        $verdeling="AAABBE";
        break;
        case(3 || 9):
        $verdeling="AAAABC";
        break;
        case(4 || 10):
        $verdeling="AABBBD";
        break;
        case(5 || 11):
        $verdeling="ABBBCC";
        break;
        case(6 || 12):
        $verdeling="AABCCC";
        break;
        }
    endif;  

echo "weegfactor ",$weegfactor . '</br>' ;
echo "lus : ",$lus . '</br>';
echo "verdeling ",$verdeling;

?>

The outcome of the above code is: weegfactor 67 lus : 12 verdeling AAABCD

Which is not correct because $verdeling should be "AABCCC". What is my mistake??

3 Answers3

1

1 || 7 evaluates to a boolean type. So your program is doing a boolean comparison of $lus and (1 || 7).

You will need to use two separate case statements for each:

switch($lus){
    case(1):
    case(7):
        $verdeling="AAABCD";
        break;
    case(2):
    case(8):
        $verdeling="AAABBE";
        break;
    case(3):
    case(9):
        $verdeling="AAAABC";
        break;
    case(4):
    case(10):
        $verdeling="AABBBD";
        break;
    case(5):
    case(11):
        $verdeling="ABBBCC";
        break;
    case(6):
    case(12):
        $verdeling="AABCCC";
        break;
}
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47
0

With case (x || y) you probably mean when it is x or y. In that case you should do this:

switch($lus) {
   case x:
   case y:
      // do stuff
      break;
}

What you have now is a check against x || y, which is always resolves to a "truish" value, just like your value 12 is "truish", making the switch take the first branch.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
0

The value of 1 || 7 is TRUE, because both 1 and 7 are truthy. So the first case is equivalent to:

case TRUE:

And in fact, all your cases are equivalent to case TRUE:.

So it's then testing $lus == TRUE. When comparing any type to a boolean, the other type is first converted to boolean (see Comparison Operators for the complete list of how loose comparisons of different types are done). Since 12 is truthy (any non-zero integer is truthy), this comparison succeeds.

If you want to test against multiple values, use multiple case statements:

case 1:
case 7:
    $verdeling="AAABCD";
    break;
Barmar
  • 741,623
  • 53
  • 500
  • 612