tags:

views:

45

answers:

2
<?php
$var = 0;
switch($var) {
   case "a":
      echo "I think var is a";
   break;
   case "b":
      echo "I think var is b";
   break;
   case "c":
      echo "I think var is c";
   break;
   default:
      echo "I know var is $var";
   break;
}
?>

Maybe someone else will find this fascinating and have an answer. If you run this, it outputs I think the var is a when clearly it's 0. Now, I'm most certain this has something to do with the fact that we're using strings in our switch statement but the variable we're checking is an integer. Does anyone know why PHP behaves this way? It's nothing too major, but it did give me a bit of a headache today.

Thanks folks!

+1  A: 

In PHP, when you compare a string and an integer, whether it be in a switch statement or using the regular comparison operators, the string is converted to an integer (unless you're using the === operator).

And when converting a string to an integer, a string that doesn't start with either a digit or a sign is always converted to 0.

See the documentation here and here.

Syntactic
I agree with what you said. However, doesn't explain why the first switch statement is getting activated. In the code I provided, aren't we comparing an integer to a string instead of vice versa?
Levi Hackwith
It doesn't matter. Look at the first link I posted, at the table called "Comparison with Various Types". Regardless of which order the operands are in, whenever strings and numbers are compared, the strings will be converted to numbers.
Syntactic
A somewhat hacky way to get around this would be to switch on `true` and have the case be something like `($var === "a")`. You can switch on constants with variable cases in C; I'm pretty sure it'll work in PHP too.
Syntactic
+4  A: 

If you compare an integer with a string, the string is converted to a number. So effectively your snippet is equivalent to:

$var = 0;
switch($var) {
   case 0: // "a" gets converted to 0.
      echo "I think var is a";
   break;
   case 0: // "b" gets converted to 0.
      echo "I think var is b";
   break;
   case 0: // "c" gets converted to 0.
      echo "I think var is c";
   break;
   default:
      echo "I know var is $var";
   break;
}

Which will produce I think var is a as output as the first case body gets executed. Even though there are 3 candidates, the first one is selected because it appears at the top.

codaddict