0

I've heard that php switch uses loose comparison. But what is the logic behind this behavior:

$var = 'default';
  switch ( $var ) {
    case 1:
      echo '1';
    break;
    case 2:
      echo '2';
    break;
    case 0:
      echo 'unexpected, huh!';
    break;
    default:
      echo 'default';
  }

It echoes the result under the case 0! Why does it think that the 'default' string is equal to 0?

Sorry for my English!

Eugeny K
  • 56
  • 3
  • 2
    By default variable `$var` is treated as int in `case` and `switch`. You should put `string` before the matching condition https://3v4l.org/q92KN – Rakesh Jakhar Mar 15 '20 at 06:14
  • 1
    use it as string `case "0": echo "something"; break;` ... – Tanker Mar 15 '20 at 06:56
  • Thank you guys, I made it with `if ( === ) {}` conditional. Though the loose comparison feature cost me several hours. – Eugeny K Mar 15 '20 at 09:23

0 Answers0