1

I want to sort an array using asort() and limit the number of elements to return.

Let me give an exeample:

$words = array (
["lorem"]=>
int(2)
["sssss"]=>
int(2)
["dolor"]=>
int(4)
["ipsum"]=>
int(2)
["title"]=>
int(1) );

with =limit = 2 I would want to have in return:

  $words = array (
    ["dolor"]=>
    int(4)    
    ["lorem"]=>
    int(2));

In other words, I'll have to sort and return only the first occurances based on $limit

any idea ?

2 Answers 2

9

You could use array_slice

asort($words);
$result = array_slice($words, 0, $limit);
Sign up to request clarification or add additional context in comments.

Comments

2

You can't apply a limit to asort() but this is a workaround.

<?php 
   $words = array("Cat", "Dog", "Donkey");
   $sorted = asort($words);
   $limit = 2;
   $final = array();
   for ($i = 0; $i <= ($limit - 1); $i++) {
       $final[] = $words[$i];
   }
   var_dump($final);
?>

Hope this helps.

4 Comments

The second one makes no sense. He wants the two highest sorted-order elements, not the first two in sorted-order.
Yes thank you, removed the unneeded solution. array_slice is a much better solution either way. Cheers.
Your solution is completely valid and easy to understand.
Note asort returns a boolean, and asort is designed for associative array.

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.