6

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

1
  • array_shift() will also do fine. Commented Dec 19, 2009 at 4:12

3 Answers 3

9

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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!
0

Use this (PHP 5.5+):

echo reset(array_column($this->data, 'id'));

1 Comment

Could you provide an explenation with your code? It might help OP or future users more.
0

I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.

After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.

Here is a sample start array:

    $myArray = array(
    'referrer' => array(
        'week' => array(
            '201901' => array(
                'Internal' => array(
                    'page' => array(
                        'number' => 201,
                        'visits' => 5
                    )
                ),
                'External' => array(
                    'page' => array(
                        'number' => 121,
                        'visits' => 1
                    )
                ),
            ),
            '201902' => array(
                'Social' => array(
                    'page' => array(
                        'number' => 921,
                        'visits' => 100
                    )
                ),
                'External' => array(
                    'page' => array(
                        'number' => 88,
                        'visits' => 4
                    )
                ),
            )
        )
    )
);

As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:

function getFirstKeys($arr){
    $keys = '';
    reset($arr);
    $key = key($arr);
    $arr1 = $arr[$key];
    if (is_array($arr1)){
        $keys .= $key . '|'. getFirstKeys($arr1);
    } else {
        $keys = $key;
    }
    return $keys;
}

When the function is called using the code:

$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';

the output is:

Get First Keys

  • The keys are: referrer|week|201901|Internal|page|number

I hope this saves someone a bit of time should they encounter a similar problem.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.