NYCPHP Meetup

NYPHP.org

[nycphp-talk] Re: Weird Switch Behavior

Michael Southwell michael.southwell at nyphp.com
Tue Sep 9 23:00:20 EDT 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.

That's not it. Your $tmp array has three elements; the first two 
elements are 1 and 2, and those elements have associative (that is, 
string) keys, foo and bar respectively. Your third element is zap, and 
it has no key specified. When PHP is given an array element with no key 
specified, it uses the next available integer. In this case, that is 0. 
So PHP is understanding this: 0 => 'zap' which is exactly what your 
output shows:

>> [foo][1]
>> [bar][2]
>> [0][zap]
> 


-- 
=================
Michael Southwell
Vice President, Education
NYPHP TRAINING:  http://nyphp.com/Training/Indepth



More information about the talk mailing list