views:

597

answers:

1

I would like to retrieve the first key from this multi-dimensional array.

Array
(
    [User] => Array
        (
            [id] => 2
            [firstname] => first
            [lastname] => last
            [phone] => 123-1456
            [email] => 
            [website] => 
            [group_id] => 1
            [company_id] => 1
        )

)

This array is stored in $this->data.

Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.

Are there any other ways to retrieve this result?

Thanks

+3  A: 

There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:

$keys=array_keys($this->data);
echo $keys[0]; //prints first key

foreach ($this->data as $key => $value)
{
    echo $key;
    break;
}

As you can see both are sloppy.

If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:

reset($this->data);

reset():

reset() rewinds array 's internal pointer to the first element and returns the value of the first array element.

But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?

ryeguy
Hmm I think I will use that method instead. According to the PHP manual key() is defined as ""key() returns the index element of the current array position. "" So, if by some reason we arent at the very first array position, it will return the incorrect key.
Check my edit.
ryeguy
Thanks, I will stick with key().
Sorry I just saw your last edit (I think edits take a minute or so to post up)...reset() was exactly what I was looking for. I don't know why the array wouldn't be at the first position but id rather be safe than sorry!