Is it *really* an associative array?

From: Date: Thu, 13 Sep 2001 15:31:05 +0000
Subject: Is it *really* an associative array?
Groups: php.general 
Request: Send a blank email to php-general+get-67228@lists.php.net to get a copy of this message
Sample code: <script language="php"> $array = array( "one", "two", "three" ); while( list( $key, $val ) = each( $array )) { if( is_string( $key )) { echo "Key is a string\n"; } echo "Key: $key => $val :Val\n"; } echo "\n\n"; $array = array( "SS" => "one", "15" => "two", "19" => "three" ); while( list( $key, $val ) = each( $array )) { if( is_string( $key )) { echo "Key is a string\n"; } echo "Key: $key => $val :Val\n"; } </script> Because of the loose typing in PHP, essentially all arrays are associative arrays. Running the script above produces the following results: ------------------------ BEGIN RESULTS Key: 0 => one :Val Key: 1 => two :Val Key: 2 => three :Val Key is a string Key: SS => one :Val Key: 15 => two :Val Key: 19 => three :Val ------------------------ END RESULTS Anyways, I want to be able to pass an array to a function. This array can be defined by me as associative (as the second array in the sample) or regular (as the first). However, I need to be able to tell one from the other in my function. As you can see, I can't do it with the is_string() function because it doesn't realize that the "15" and the "19" I specify as keys in the second declaration are actually strings that I added and not actual element numbers. Is there some way that I can determine if the keys of an array are user defined (ie, a user defined associative array) and not the keys PHP defines due to the fact that they are the element numbers? Another, somewhat related issue, notice the funkiness that happens when you run the following, similar, script: <script language="php"> $array = array( "one", "two", "three" ); while( list( $key, $val ) = each( $array )) { if( is_string( $key )) { echo "Key is a string\n"; } echo "Key: $key => $val :Val\n"; } echo "\n\n"; for( $i = 0; $i < count( $array ); $i++ ) { echo "Printing element: $i -- " . $array["$i"] . "\n"; } echo "\n\n"; $array = array( "SS" => "one", "15" => "two", "three" ); while( list( $key, $val ) = each( $array )) { if( is_string( $key )) { echo "Key is a string\n"; } echo "Key: $key => $val :Val\n"; } echo "\n\n"; for( $i = 0; $i < 20; $i++ ) { echo "Printing element: $i -- " . $array["$i"] . "\n"; } </script> Any help anyone can provide would be *greatly* appreciated!! Chris

« previous php.general (#67228) next »