-1

I have a strange case issue, in my php code;

$sm_hours = (int)$sm_hours;  // Make it an integer

echo $sm_hours;  // is 206

    switch ($sm_hours) {
        case ($sm_hours = 0 && $sm_hours <= 120):
            echo "One";
        break;
        case ($sm_hours >= 121 && $sm_hours <= 240):
            echo "Two";
        break;
        case ($sm_hours >= 241):
            echo "Three";
        break;
    }

$sm_hours is 206 but the echo I get is One not Two. What have I missed?

Thanks

HeavyHead
  • 310
  • 3
  • 11

6 Answers6

1

You will always jump into the first switch case because you are setting $sm_hours to 0. A single = is used to set the variable.

To test its value use == which will perform type juggling, or use === to test the type also.

Simian
  • 814
  • 11
  • 21
1
 case ($sm_hours == 0 && $sm_hours <= 120):

you are using equality operator

undefined_variable
  • 6,180
  • 2
  • 22
  • 37
1

In case one, try this:

case ($sm_hours == 0 && $sm_hours <= 120):
    echo "One";
break;
user3461434
  • 174
  • 2
  • 13
1

Better use if and elseif statements in your case:

$sm_hours = (int)$sm_hours;  // Make it an integer
echo $sm_hours;  // is 206

if ($sm_hours >= 0 && $sm_hours <= 120)
    echo "One";
elseif ($sm_hours >= 121 && $sm_hours <= 240)
    echo "Two";
else
    echo "Three";

switch just tries to match exact values.

WeSee
  • 3,158
  • 2
  • 30
  • 58
0

try

 $sm_hours >= 0 && $sm_hours <=120
Bug Hunter 219
  • 312
  • 1
  • 14
  • can you explain, why his code is not working? – swidmann Nov 21 '15 at 13:39
  • the switch statement gets converted to switch(260(boolean)) as int is a boolean value.In the first statement $variable gets updated to 0 which returns a boolean true and when it is compared with 120 it always evaluate to true as 0 < 120 and hence the boolean value becomes true and a match occurs and hence the condition is evaluated – Bug Hunter 219 Nov 21 '15 at 13:41
  • I thought you would point to the assignment instead of the comparision here: `sm_hours = 0` – swidmann Nov 21 '15 at 13:45
  • 1
    The solution that the OP has accepted is not logically correct . Consider when the value of variable is less than 120 and > 0 .Logically first condition nets to get accepted but it won't happen and hence it is logically flawed – Bug Hunter 219 Nov 21 '15 at 13:48
0

Ok, so this works taking into account where $sm_hours is < 120 as pointed out by Anand. This code works for all options that I need.

     switch ($sm_hours) {
        case ($sm_hours >= 121 && $sm_hours <= 240):
            echo "Two";
        break;
        case ($sm_hours >= 241):
            echo "Three";
        break;
        default:
            echo "One";
        break;
     }
HeavyHead
  • 310
  • 3
  • 11