Elric Wamugu
Elric Wamugu

Reputation: 133

Get the 1st 5 largest values from an array

i am trying to get the 1st 5 largest values from a numeric array...i have tried using the rsort() function to list the array values from highest to lowest but cant get a way to pick the 1st 5 from the result.

Upvotes: 2

Views: 6484

Answers (4)

knittl
knittl

Reputation: 265687

Using array_slice:

$a = array ( 1, 3, 4, 2, 4, 5, 10, 7, 6, 8, 0 );
rsort($a);
$largest = array_slice($a, 0, 5);

Upvotes: 10

Wasim Karani
Wasim Karani

Reputation: 8886

Check this out

$array_b4_change=array("knittl", "limón", "naranja", "plátano", "manzana" , "vikas" ,"wazzzy");
rsort($array_b4_change);

Use

array_slice($array_b4_change, 0, 5);

Upvotes: 3

garnertb
garnertb

Reputation: 9594

After you rsort just slice the array using array_slice:

$ouput = array_slice($array, 0, 5);

Upvotes: 2

Jonas m
Jonas m

Reputation: 2734

If you already have the array organized you could output it with

for ($i = 0; $i <= 4; $i++) {
    print $array[$i];
}

Upvotes: 0

Related Questions