since when does 0=="ug" ?? The output of this script is "ug":

$val = 0;

switch($val) {
        case "ug":
                echo "ug\n"; // this line of code gets executed
                break;
        case "gd":
                echo "gd\n";
                break;
        case "cc":
                echo "cc\n";
                break;
        case "jr":
                echo "jr\n";
                break;
        default:
                throw new Exception("not a valid college type");
}

I see from the docs that switch does a loose comparison but this behavior seems totally wrong to me.

    Interesting (if annoying). I played around a little bit, and found that if I cast $val to a string then it worked.

    $val = 0;
    switch((string) $val) {
    // ...
    

    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.
    https://www.php.net/manual/en/language.operators.comparison.php

    Weedpacket While this does make sense, I still consider this a bug. You have an empty value that is considered equal to a non-empty string.

      Yeah, I try to avoid mixing types ad hoc for this very reason. I've seen way too many bugs that result from chucking values of random types about and the resulting necessity to constantly check and recheck what types any particular variable contains ("is this an array or a string? Oh, it's FALSE. No. wait: Null").

      I agree treating numeric strings as integers even in string context is a mistake on the part of the language—I've been bitten by that before when I tried to index an array of countries by ISO3166 numeric code. But if you try submitting it as a bug I guarantee it'll be marked WONTFIX because it would break way too much existing code.

      In fact, I'm not using switches that much either because they operate with only a loose idea of equality.

      $return = ['ug' => 'ug', 'gd' => 'gd', 'cc' => 'cc', 'jr' => 'jr'][$val] ?? null;
      if(isset($return))
          echo $return;
      else
          throw new Exception("...");
      

      It would be even shorter if you could have a throw directly on the right of the ?? operator...

        Write a Reply...