Re: array key's: which is correct?

From: Date: Tue, 08 Jun 2010 14:35:06 +0000
Subject: Re: array key's: which is correct?
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-305957@lists.php.net to get a copy of this message
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

« previous php.general (#305957) next »