NYCPHP Meetup

NYPHP.org

[nycphp-talk] Re: Weird Switch Behavior

Darryle Steplight dsteplight at gmail.com
Tue Sep 9 22:56:05 EDT 2008


Hi Michael,
  Switch isn't the problem. Arrays are going to behave like  Arrays no
matter how you choose to loop through them.

$tmp = array('foo','bar','zap');  is the same as typing

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

If you don't specify the index, PHP will start using numbers starting
at zero as array keys. So in your example, you basically ended up
doing this
$tmp = array(
      ' foo ' =>1,
      ' bar ' =>2,
       ' 0 '=>'zap');

I hope this helps clarify things.


On Tue, Sep 9, 2008 at 10:44 PM, Michael B Allen <ioplex at gmail.com> 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]
>
> --
> 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