get only 5 elements from array

11,354

Solution 1

As far as I know there isn't.

You could use a heap for this, but for only 5 elements I'm not sure it's faster than just storing the top 5.

Solution 2

Sort the array by the weight value in descending order and then get the first five values:

function cmpByWeight($a, $b) {
    return $b['weight'] - $a['weight'];
}
uasort($array, 'cmpByWeight');
$firstFive = array_slice($array, 0, 5);

Solution 3

You'd be better using uasort with a callback that compares the 'weight' index of the passed values, and then array_slice to grab the first 5 elements (or last 5 depending on which way you sort...)

Share:
11,354

Related videos on Youtube

cupakob
Author by

cupakob

CleanCode- und OpenSource/Linux-Enthusiast

Updated on June 04, 2022

Comments

  • cupakob
    cupakob almost 2 years

    my array is setup as follow:

    array
      'testuri/abc' => 
        array
          'label' => string 'abc' (length=3)
          'weight' => float 5
      'testuri/abd' => 
        array
          'label' => string 'abd' (length=3)
          'weight' => float 2
      'testuri/dess' => 
        array
          'label' => string 'dess' (length=4)
          'weight' => float 2
      'testuri/gdm' => 
        array
          'label' => string 'gdm' (length=3)
          'weight' => float 2
      'testuri/abe' => 
        array
          'label' => string 'abe' (length=3)
          'weight' => float 2
      'testuri/esy' => 
        array
          'label' => string 'esy' (length=3)
          'weight' => float 2
      'testuri/rdx' => 
        array
          'label' => string 'rdx' (length=3)
          'weight' => float 3
      'testuri/tfc' => 
        array
          'label' => string 'tfc' (length=3)
          'weight' => float 3
    

    I want to get/filter the 5 elements with bigges 'weight'. Is there a php function to make this?

    PS. My idea was to use foreach

  • Greg
    Greg almost 15 years
    usort won't preserve the array-keys