Question

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 ?

Was it helpful?

Solution

You could use array_slice

asort($words);
$result = array_slice($words, 0, $limit);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top