Re: test for associative or numerically indexed array

From: Date: Thu, 20 Mar 2003 08:57:47 +0000
Subject: Re: test for associative or numerically indexed array
References: 1 2 3 4  Groups: php.general 
Request: Send a blank email to php-general+get-140408@lists.php.net to get a copy of this message
> At 08:52 20.03.2003, cpaul said: > --------------------[snip]-------------------- > >ok thanks - that makes sense. sort of doesn't solve my problem, because > >if my function receives an enumerated array, i want it to treat it as an > >associative array, using the value as the key. > --------------------[snip]-------------------- ernest wrote: > What would be the value then? > > If I get you correctly, you would treat an array that comes like > [0] => entry 0 > [1] => entry 1 > [2] => entry 2 like this: 'entry 0' => 'entry 0' 'entry 1' => 'entry 1' 'entry 2' => 'entry 2' > What happens when there are duplicate values in the source array? You will > loose entries on duplicate values. the source array is based on a directory listing, so i don't think there's a possibility of that happening? > You can't tell with absolute certainty if an array is enumerated, or built > 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? 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? > What you can do is walk the array keys and check if there is at least a > single non-numeric key. If you found one the array is associative. If you > found none it may be likely that the array is enumerated, but you can't be > sure in a general way, except your application is designed in a way that > uses always non-numeric keys for associative arrays. thanks so much for all your input on this. regards -- chris paul

« previous php.general (#140408) next »