Retrieve first key in multi-dimensional array using PHP

12,761

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?

Share:
12,761
user103219
Author by

user103219

Updated on June 17, 2022

Comments

  • user103219
    user103219 almost 2 years

    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

  • user103219
    user103219 over 14 years
    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.
  • user103219
    user103219 over 14 years
    Thanks, I will stick with key().
  • user103219
    user103219 over 14 years
    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!
  • Bono
    Bono over 8 years
    Could you provide an explenation with your code? It might help OP or future users more.