The switch-case experiment
After the little experiment with PHP type comparison operation, I tried to find out what sort of comparison test the PHP switch-case statement enforces. The following is the code:
$cmd = 0;
switch($cmd)
{
case 'test': echo 'Inside Test case'; break;
default : echo 'Inside default case'; break;
}
To my surprise, the output was ‘Inside Test case’. The switch-case statement performs loose comparison behind the scene! If the case constructs construct perform complicated operations such as database manipulation or file handling, a zero parameter to the switch will create unwanted side-effects. This can be avoided if a case for handling zero input is inserted as the first case of the switch.
case 0 : /*do nothing*/ break;
However, if the 0 parameter comes directly from user via HTTP GET or POST request, it is automatically converted to a string and will not compare equal to any other string except maybe the empty string. You don’t need to add the zero case there.
October 6, 2008 at 9:17 pm
btw it’s often better to start with the default: when nothing is switched, internally in PHP it’s a lot faster because of less loops, usually default is where you start and then select something in a case, exactly the other way around
Like:
switch($_GET['foo']) {
default: $bar = $z; break;
case ‘x’: $bar = $y; break;
case ‘y’; $bar = $x; break;
}