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

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



2009/8/20 Keith <survivor_bus@xxxxxxxxxxx>:
> 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
>
>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux