NYCPHP Meetup

NYPHP.org

[nycphp-talk] Re: Weird Switch Behavior

Ken Robinson kenrbnsn at rbnsn.com
Tue Sep 9 23:57:15 EDT 2008


At 10:44 PM 9/9/2008, Michael B Allen wrote:
>On Tue, Sep 9, 2008 at 10:31 PM, Michael B Allen <ioplex at gmail.com> wrote:
> > Can someone explain why the below switch matches the 0 element?
> >
> > $ cat switch.php
> > <?php
> >
> > $tmp = array(
> >        'foo' => 1,
> >        'bar' => 2,
> >        'zap',
> > );
> >
> > foreach ($tmp as $key => $val) {
>
>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]

Here's one way to make switch behave the way you want:

<?php


$tmp = array(
         'foo' => 1,
         'bar' => 2,
         'zap',
);


foreach ($tmp as $key => $val) {
         switch (true) {
                 case $key === 'foo':
                 case $key === 'bar':
                         echo "[$key][$val]\n";
                         break;
         }
}
?>


Ken 




More information about the talk mailing list