1

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)?

2
  • Whoops, misread. Can't delete. Disregard. :) Commented Jan 22, 2014 at 20:54
  • @SenorAmor - nick of time ;) Commented Jan 22, 2014 at 20:57

2 Answers 2

3

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

reset($arr);
$key = key($arr);
Sign up to request clarification or add additional context in comments.

3 Comments

Now the only question is which came first, the key or the array? :D
I tried it and key is empty in my case. :( *Edit: If I understand the php.net documentation, reset returns a string, and so I can't get the key from a string.
@koljanep You're right, that was too fast, you need to reset the array seperately and then get the key, see my edit: codepad.viper-7.com/23fMsh
3

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];

1 Comment

+1 You were right, you need to do it in two steps. I wonder why it was downvoted though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.