Top two elements of an associative array in php?

For getting both key and value I would go this way: arsort($data); $result = array_slice($data,0,2).

1, gets the keys too. – Jonah Dec 14 '10 at 23:11.

Asort($data); $first = array_pop($data); $second = array_pop($data); Notice that instead of putting it in reverse order and grabbing the first items, I put it in order and grabbed the last items.

1 Agree with this one. Could just as easily stick with arsort() and use array_shift() instead though. – simshaun Dec 14 '10 at 22:59 @simshaun: Yes... it just makes more sense (to me) to grab the last two items in order than the first two items out of order.

– Jonah Dec 14 '10 at 23:00 1 Just be aware, that it actually removes elements from the array. Also, you're not getting a key, which seems to be what OP wants. – Mchl Dec 14 '10 at 23:01 @Mchl: Yes, excellent point.

But then, so does the OP's code; he apparently doesn't care. – Jonah Dec 14 '10 at 23:02.

Your code is correct, you just have some extra calls there arsort($data); $first = each($data); $second = each($data); should be enough. You need to be more specific though about what exactly you want to get. Each returns an array of four elements - is this what you want?

Something like this: $array = array ( 'wood' => 2, 'metal' => 1, 'blah' => 4 ); $first = end($array); $second = prev($array).

That would not work unless the array was already sorted in ascending order. – simshaun Dec 14 '10 at 22:58.

Maybe not exactly what a Priority Queue was intended for and regular array sorting and extracting functions are completely fine either, but to add something new: $queue = new SplPriorityQueue; $queue->setExtractFlags(SplPriorityQueue::EXTR_BOTH); $queue->insert('wood', 2); $queue->insert('metal', 5); $queue->insert('plastic', 3); This is automatically sorted in descending order of the numeric value. To get the elements, do var_dump( $queue->extract(), $queue->extract() ); would give (codepad) array(2) { "data"=> string(5) "metal", "priority"=> int(5) } array(2) { "data"=> string(7) "plastic", "priority"=> int(3) } and leaves $queue containing only 'wood' then. In addition to the SplPriorityQueue, you could also use an SplMaxHeap.

Read more at: Matthew Turland's Blog: New SPL Features in PHP 5.3 and PHP SPL Reference Documentation.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions