Re: test for associative or numerically indexed array

From: Date: Thu, 20 Mar 2003 10:34:22 +0000
Subject: Re: test for associative or numerically indexed array
References: 1 2 3 4 5  Groups: php.general 
Request: Send a blank email to php-general+get-140412@lists.php.net to get a copy of this message
At 09:57 20.03.2003, cpaul said: --------------------[snip]-------------------- >> as associative array. Take this example: >> $a = array('one','two','three'); >> $b = array(); $b[0] = 'one'; $b[1] = 'two'; $b[2] = >> 'three'; >> $c = array(0 => 'one', 1 => 'two', 2 => >> 'three'); >> >> Which one would you believe is enumerated, and which one is associative? > >they'd all be enumerated, except perhaps $c -- but i've grown :) and now >understand that $c winds up being an enumerated array.. or is it? Well, all these 3 arrays are _exactly_ the same. If you print_r() them you'd see Array { 0 => one 1 => two 2 => three } The key to this issue seems to be understanding that it makes no difference how the array keys are constructed... an array is an association of key to value, being a hash always if you want to see it that way. >in my code.... > > $q = mysql_query ( "SELECT production_id, title FROM productions ORDER >BY title;" ); > $this->all_productions[""] = ""; > while ( $row = mysql_fetch_array( $q ) ) { > $this->all_productions[$row["production_id"]] = $row["title"]; > } > >the array is kept in order when i foreach the array - wouldn't they sort >themselves into 0,1,2,3,4,5,etc if my while loop was populating an >enumerated array? or are all arrays in php actually a keyed hash? You're chosing your own keys here - so this makes a perfect associative array, even if the keys ($row['production_id']) would be a sequenced number. If you would just add the titles up ($this->all_productions[] = $row['title']), PHP would choose an index key for you - the most general thing it can do is to enumerate it. Basically what it does is array[count(array)] = new_element So much for the "theory" - what are you really trying to achieve? Maybe there's something you can redesign so you're not relying on the fact if an array is "enumerated" or not. -- >O Ernest E. Vogelsinger (\) ICQ #13394035 ^ http://www.vogelsinger.at/

« previous php.general (#140412) next »