Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve first key in multi-dimensional array using PHP

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

like image 506
user103219 Avatar asked Aug 25 '09 17:08

user103219


1 Answers

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?

like image 93
ryeguy Avatar answered Oct 05 '22 22:10

ryeguy