1

I am using a switch to test the value of a variable.
The variable, $sizeTotal, could contain either a string or a number. In the below example, I am expecting the switch to trigger the default case.
However, it goes to the first case every time and I don't know why...

$sizeTotal = "test";
$extraCharges['2'] = 1000;

switch ($sizeTotal) {
    case ($sizeTotal < $extraCharges['2']):
        $var = 40;
        return $var;

    case ($sizeTotal >= $extraCharges['2']):  
        $var = 60;
        return $var;

    default:
        $var = 1000;
        return $var;
}
2
  • 3
    You're using the switch statement wrong, it's meant for checking a single value of a variable, not a condition. You probably want to use an else-if construction which IS able to check conditions. php.net/manual/en/control-structures.switch.php
    – Niels
    Commented Dec 28, 2017 at 13:20
  • 1
    The string is converted to 0 and 0 is less than 1000. that is why your first condition is true. Commented Dec 28, 2017 at 13:38

1 Answer 1

6

From the docs

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

You're placing a string in a comparison.

Not the answer you're looking for? Browse other questions tagged or ask your own question.