Reputation: 868
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
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
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