Comparison of Null, Empty String and Boolean in Switch Statement - PHP
I found a little bug in an application I worked on that made me inquire more into how some things work.
Here is my code snippet
function test($var = '')
{
switch($var)
{
case 0:
//Do something
break;
case 1:
//Do something
break;
default:
//Defualt
}
}
Now, here is the gist. When this function is called without a variable it enters into the 0 case. Naturally you would have expected it to be picked by the default case. Passing null and false (boolean) as the variable still gets into the 0 case. I guess this was so because switch case does an equivalent comparison, then equaling null, false and empty strings to 0.
The best way to solve this is to use an if..else if..if statement and do a strict comparison using ===. Below is a better way to solve it.
function test($var = '')
{
if ($var === 0) {
//Do Something
} else if($var === 1) {
//Do Something
} else {
//Default;
}
}
This might not really help anyone, it is just a way to keep my mind afresh.