Get key of first item in array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Get key of first item in array

Post by GeXus »

Is there a function to just get the key value of the first element in an array? Thanks!
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Get key of first item in array

Post by VladSun »

http://php.net/manual/en/function.array-shift.php
but it will remove the first element
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Get key of first item in array

Post by Weirdan »

Code: Select all

reset($array);
echo key($array);
 
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Re: Get key of first item in array

Post by GeXus »

That gives me the value of the first element thought... I want the key of the first element
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Re: Get key of first item in array

Post by GeXus »

Weirdan wrote:

Code: Select all

reset($array);
echo key($array);
  
Perfect, thank you!
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Get key of first item in array

Post by Ambush Commander »

Just be careful about the side-effects of reset() (usually not a problem)
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Get key of first item in array

Post by RobertGonzalez »

I believe array_keys() gives you all of the keys as an array as well, so you reference the key using that array as well.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Get key of first item in array

Post by VladSun »

GeXus wrote:That gives me the value of the first element thought... I want the key of the first element
Ops :) Sorry ... missed the "key" word.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
jimthunderbird
Forum Contributor
Posts: 147
Joined: Tue Jul 04, 2006 3:59 am
Location: San Francisco, CA

Re: Get key of first item in array

Post by jimthunderbird »

Everah wrote:I believe array_keys() gives you all of the keys as an array as well, so you reference the key using that array as well.
I will use this approach.
Post Reply