Kolja
Kolja

Reputation: 868

php return array key of first element?

I have an assoc array in PHP which I am sorting by value. After sorting I need to return the key of the first element.

Example array:

Array
(
    [a] => 42.857142857143
    [b] => 87.5
    [c] => 50
    [d] => 61.538461538462
)

Then I use asort(), and the array looks like this:

Array
(
    [b] => 87.5
    [d] => 61.538461538462
    [c] => 50
    [a] => 42.857142857143
)

How can I return "b" (as it is the key of the first array)?

Upvotes: 1

Views: 151

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

reset() the array pointer to the first item and then call key().

reset($array);
$key = key($array);

Or you can use array_keys().

$array_keys = array_keys($array);
$key = $array_keys[0];

Upvotes: 3

jeroen
jeroen

Reputation: 91744

You can use key() in combination with reset() to make sure you have the first element:

reset($arr);
$key = key($arr);

Upvotes: 3

Related Questions