Re: array key's: which is correct?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 8 June 2010 16:38, Ashley Sheridan <ash@xxxxxxxxxxxxxxxxxxxx> wrote:
> On Tue, 2010-06-08 at 10:35 -0400, Paul M Foster wrote:
>
>> On Tue, Jun 08, 2010 at 09:38:58AM -0400, Robert Cummings wrote:
>>
>> > Tanel Tammik wrote:
>> >> Hi,
>> >>
>> >> which one is correct or "better"?
>> >>
>> >> $array[3] = '';
>> >> or
>> >> $array['3'] = '';
>> >>
>> >> $i = 7;
>> >>
>> >> $array[$i] = '';
>> >> or
>> >> $array["$i"] = '';
>> >
>> > Sometimes it is good to illustrate the correct answer:
>> >
>> > <?php
>> >
>> > $array = array
>> > (
>> >     '1'     => '1',
>> >     '2'     => '2',
>> >     'three' => 'three',
>> >     '4.0'   => '4.0',
>> >     5.0     => 5.0,
>> > );
>> >
>> > var_dump( array_keys( $array ) );
>> >
>> > ?>
>> >
>> > The answer is surprising (well, not really :) and certainly advocates
>> > against making literal strings of integers or manually converting a
>> > string integer to a real integer or using floating point keys.
>>
>> Curse you, Rob Cummings! ;-}
>>
>> I was stunned at the results of this. I assumed that integers cast as
>> strings would remain strings as indexes. Not so. And then float indexes
>> cast to ints. Argh!
>>
>> My advice to the original poster was slightly incorrect. But I would
>> still encourage you to avoid enclosing variables in double-quotes
>> unnecessarily. (And integers in single-quotes for that matter.)
>>
>> Paul
>>
>> --
>> Paul M. Foster
>>
>
>
> The obvious way around this would be to include some sort of character
> in the index that can't be cast to an integer, so instead of $array[1.0]
> which would equate to $array[1] maybe add an underscore to make it
> $array['_1.0']. It's not the prettiest of solutions, but it does mean
> that indexes are kept as you intended, and you need only strip out the
> first character, although I imagine a lot of string manipulation on a
> large array would decrease performance.

Floats in quotes are not cast to int when used as array keys. Just an FYI :)

Regards
Peter

-- 
<hype>
WWW: http://plphp.dk / http://plind.dk
LinkedIn: http://www.linkedin.com/in/plind
BeWelcome/Couchsurfing: Fake51
Twitter: http://twitter.com/kafe15
</hype>

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




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux