I've never understood why people use switch statements like this as in
reality you are using it more like an if/else block, but anyway.

The reason why your code is not working is that you are passing into
the switch the value of 0, or false, which means that when any of
those $sum == N conditionals comes up as false (say $sum == 8 ), then
that is what is returned because they match up. In PHP's eyes, 0 ==
false in switch statements.

To fix your code, change the switch( $sum ) to switch( true ):

switch( true )
{
        case ($sum == 8):
                echo "sum=8\n";
                break;
        case ($sum == 7 || $sum == 6):
                echo "sum=7 or 6\n";
                break;
        case ($sum == 2 || $sum == 1):
                echo "sum=2 or 1\n";
                break;
        case ($sum == 0):
                echo "sum=0\n";
                break;
        default:
                echo "sum=3/4/5\n";
                break;
}

Or, write your switch like this:

switch( $sum )
{
        case 8:
                echo "sum=8\n";
                break;
        case 6:
        case 7:
                echo "sum=7 or 6\n";
                break;
        case 1:
        case 2:
                echo "sum=2 or 1\n";
                break;
        case 0:
                echo "sum=0\n";
                break;
        default:
                echo "sum=3/4/5\n";
                break;
}

Regards,

Adam.

On Thu, Aug 20, 2009 at 8:40 PM, Keith<survivor_...@hotmail.com> wrote:
> 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
>
> $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
>
>



-- 
Adam Randall
http://www.xaren.net
AIM: blitz574

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

Reply via email to