Re: Is there limitation for switch case: argument's value?

From: Date: Sun, 23 Aug 2009 02:57:12 +0000
Subject: Re: Is there limitation for switch case: argument's value?
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-297097@lists.php.net to get a copy of this message
Thanks! Torben. I got the point now and it works! :-) I'm doing this because the statements of each cases is quite long, and I wish to have minimum coding without repetition. "Lars Torben Wilson" <larstorben@gmail.com> wrote in message news:36d4833b0908202323p3c858b5fn6a1d6775aa7f8997@mail.gmail.com...
2009/8/20 Keith <survivor_bus@hotmail.com>:
Hi, I encounter a funny limitation here with switch case as below: The value for $sum is worked as expected for 1 to 8, but not for 0. When the $sum=0, the first case will be return, which is "sum=8". Is there any limitation / rules for switch case? Thanks for advice! Keith
Hi Keith, Try replacing 'switch($sum)' with 'switch(true)'. Note that unless you have very good reasons for using a switch statement like this, and know exactly why you're doing it, it's often better just to use it in the normal fashion. i.e.:
      switch ($sum)
       {
       case 8:
           break;
       case 7:
       case 6:
           break;
       case 2:
       case 1:
           break;
       case 0:
           break;
default:
           break;
       }
Some people like the syntax you've presented but honestly, there's usually a better way to do it. This is also somewhat faster too, although you may only notice the difference in very tight loops where you're counting every nanosecond. Regards, Torben
$sum=0; switch($sum) { case ($sum==8): echo "sum=8"; break;
      case ($sum==7 || $sum==6):
      echo "sum=7 or 6";
      break;
case ($sum==2 || $sum==1): echo "sum=2 or 1"; break;
      case 0:
      echo "sum=0";
      break;
default: echo "sum=3/4/5"; break; } -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php


« previous php.general (#297097) next »