On Fri, 30 Aug 2002, Cameron Thorne wrote: > Can anyone explain why the following code operates the way it does in my > comments?
Sure. > <?php > > $test = array ( 'a' => 'A', 'b' => 'B', 'c' => 'C'); An associative array, $test. > > if (array_key_exists(2, $test)) echo "It works by key number!"; // Does not > work. ... for subjective definitions of "work." It works alright. Nothing prints because there isn't an array key '2' in $test. > if (array_key_exists('c', $test)) echo "It works by key name!"; // Works. Of course. > print_r(array_keys($test)); // outputs "Array ( [0] => a [1] => b [2] => > c ) " You've done two things with this statement. (1) Got all the keys from $test, then (2) printed out the keys in "human readable" format. print_r() is printing information about the array which was returned from the call to array_keys(). Examine the output from "print_r($test)" and check the documentation for print_r() & array_keys() to get a glimpse into what might be the source of what's got you a bit confused. > ?> > Any ideas? According to the documentation, it seems like I should be able > to access any key in the array by either name or number (which is what I > want to do). You can access array indicies by number for non-associative arrays: $test = array( "A", "B", "C", "D" ); OR associative arrays that use numbers for keys: $test = array( 0 => "A", 1 => "B", 3 => "C", 4 => "D" ); echo( $test[2] ); ... will work for either of those, but the indicies of your original $test: > $test = array ( 'a' => 'A', 'b' => 'B', 'c' => 'C'); have to accessed with the appropriate key. hth, ~Chris -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php