.josh Posted December 25, 2006 Share Posted December 25, 2006 okay i'm sure this is a noob question but..damn. Anyways:just like what it says in the subject; I need to get the key of an array. For example:$row = array('a' => 1, 'b' => 2, 'c' => 3);well, according to the manual, doing key($row) gets the key of the associative array. So I tried this:$key = key($row[1]); And thought it would assign 'b' to $key, but apparently when I read further, it really assigns the key that the array's internal pointer currently points to. Close, but no cigar, as they say. So I'm looking at the functions associated with arrays in the manual, and unless I'm blind (I hope I'm blind), there doesn't seem to be a function that will simply give me the key of an associative array if I specify the position like in my example above. So..am I blind? Anybody know how I would go about getting this? I know I can combine a foreach and a condition or 2 to get what I want, such and all, but I really don't want to go to that length for my script. It just seems like there's got to be a way to just simply say "okay, here's my array and position, now what's the key for it." Quote Link to comment https://forums.phpfreaks.com/topic/31799-solved-get-the-key-of-an-array/ Share on other sites More sharing options...
Psycho Posted December 25, 2006 Share Posted December 25, 2006 $keys = array_keys($row);$key = $keys[1]; Quote Link to comment https://forums.phpfreaks.com/topic/31799-solved-get-the-key-of-an-array/#findComment-147462 Share on other sites More sharing options...
.josh Posted December 25, 2006 Author Share Posted December 25, 2006 well damn, i dunno why i didn't think of that. maybe it's the alcohol...thanks! Quote Link to comment https://forums.phpfreaks.com/topic/31799-solved-get-the-key-of-an-array/#findComment-147486 Share on other sites More sharing options...
Barand Posted December 25, 2006 Share Posted December 25, 2006 or if you want the key of the item whose value is 2$key = array_search('2', $row);PS Merry Christmas Quote Link to comment https://forums.phpfreaks.com/topic/31799-solved-get-the-key-of-an-array/#findComment-147507 Share on other sites More sharing options...
Psycho Posted December 25, 2006 Share Posted December 25, 2006 Aha! You could combine Barand's and my suggestions to get a single line solution to get the key by index number (assuming there are no duplicate values)$key = array_search($row[1], $row); Quote Link to comment https://forums.phpfreaks.com/topic/31799-solved-get-the-key-of-an-array/#findComment-147582 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.