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;
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.

One thought on “The switch-case experiment

  1. 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 🙂


    switch($_GET[‘foo’]) {

    default: $bar = $z; break;

    case ‘x’: $bar = $y; break;
    case ‘y’; $bar = $x; break;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s