Page 1 of 1

Get key of first item in array

Posted: Sat Jan 12, 2008 3:34 pm
by GeXus
Is there a function to just get the key value of the first element in an array? Thanks!

Re: Get key of first item in array

Posted: Sat Jan 12, 2008 3:38 pm
by VladSun
http://php.net/manual/en/function.array-shift.php
but it will remove the first element

Re: Get key of first item in array

Posted: Sat Jan 12, 2008 3:41 pm
by Weirdan

Code: Select all

reset($array);
echo key($array);
 

Re: Get key of first item in array

Posted: Sat Jan 12, 2008 3:42 pm
by GeXus
That gives me the value of the first element thought... I want the key of the first element

Re: Get key of first item in array

Posted: Sat Jan 12, 2008 3:43 pm
by GeXus
Weirdan wrote:

Code: Select all

reset($array);
echo key($array);
  
Perfect, thank you!

Re: Get key of first item in array

Posted: Sat Jan 12, 2008 4:32 pm
by Ambush Commander
Just be careful about the side-effects of reset() (usually not a problem)

Re: Get key of first item in array

Posted: Sat Jan 12, 2008 5:05 pm
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.

Re: Get key of first item in array

Posted: Sun Jan 13, 2008 9:52 am
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.

Re: Get key of first item in array

Posted: Sun Jan 13, 2008 2:02 pm
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.