0

I have run into a puzzling issue in PHP switch statements

    $strKey = 0;
    $answer = null;
    switch($strKey){
        case 'intProductionOrder':
            $answer = 'intProductionOrder';
            break;
        case 'second':
            $answer = 'second';
            break;
        default:
            $answer = 'default';
    }
    echo $answer;

Should return default but it does not, it returns intProductionOrder, why?

pvg
  • 2,673
  • 4
  • 17
  • 31
Ruttyj
  • 853
  • 2
  • 11
  • 18

2 Answers2

1

Check out this post for why: Why does PHP consider 0 to be equal to a string?

The strings in your case statements get cast to ints before comparing and then it drops into the first case statement. Use strval() in the switch statement to fix that and force comparing strings.

pucky124
  • 1,489
  • 12
  • 24
1

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

Marco
  • 2,007
  • 17
  • 28