NYCPHP Meetup

NYPHP.org

[nycphp-talk] Re: Weird Switch Behavior

Darryle Steplight dsteplight at gmail.com
Tue Sep 9 23:59:32 EDT 2008


Hi Mike,
   It kind of sounds like you are talking about two different things
or at least the confusion involves two different topics. Basically, if
you are going to use a Switch statement it's a good practice to keep
the case expression within quotation, if you want to get desired
results.

 Also, be very careful when doing ,
SWITCH($foo)
{
case  ' 5 ' :
case ' 6 ' :
    do execute some code...
break;
default:
break;
}

also 5 is an interger, but ' 5 ' is a string. So that will make a
difference when comparing it to $foo. Take a look at
http://us.php.net/intval for more details.


The above statement says if $foo equals 5 or 6 then execute some code.

On Tue, Sep 9, 2008 at 11:45 PM, Michael B Allen <ioplex at gmail.com> wrote:
> On Tue, Sep 9, 2008 at 10:56 PM, Hans Zaunere <lists at zaunere.com> wrote:
>>> Nevermind - $key is an int so 'foo' is being cast to an int which
>>> evaluates to 0.
>>>
>>> I think I would prefer that switch be a little more explicit.
>>>
>>> >        switch ($key) {
>>> >                case 'foo':
>>> >                case 'bar':
>>> >                        echo "[$key][$val]\n";
>>> >                        break;
>>> >        }
>>> > }
>>> >
>>> > $ php -f switch.php
>>> > [foo][1]
>>> > [bar][2]
>>> > [0][zap]
>>
>> Should switch be more explicit, or should the programmer? :)  Don't depend
>> on auto type casting...
>
> That's what I'm saying.
>
> In this case PHP looks at $key and sees (int)0. So now it auto type
> casts 'foo' to an int which for any string yields (int)0 and thus the
> case matches the 0 => 'zap' element unexpectedly. If switch used a
> typed comparison it would not auto type cast and it would compare
> (int)0 to (string)'foo' and because the types do not match I would get
> the expected results.
>
> But of course if switch used a typed comparison you would have to code
> something like:
>
>  $str = '5';
>  switch ($str) {
>      case 5:
>          // no match ?!
>          break;
>      case 'foo':
>          ...
>
> as:
>
>  $str = '5';
>  switch ($str) {
>      case 5:
>      case '5':
>          // ahhh, now it matches
>          break;
>      case 'foo':
>          ...
>
> with double cases which people would no doubt be hee'n and haw'n over to no end.
>
> M
>
> --
> Michael B Allen
> PHP Active Directory SPNEGO SSO
> http://www.ioplex.com/
> _______________________________________________
> New York PHP Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> NYPHPCon 2006 Presentations Online
> http://www.nyphpcon.com
>
> Show Your Participation in New York PHP
> http://www.nyphp.org/show_participation.php
>



More information about the talk mailing list