7

this question looks like it should have a simple answer but google and the php manual are being no help to me, maybe I just don't understand what they are telling me.

I have an array example:

$outcomes_array = array(1,4,2,3,5);

It will always contain just numbers, how do I go about sorting this array so that it is always in descending order?

so output I want:

$outcomes_array[0] = 5
$outcomes_array[1] = 4
$outcomes_array[2] = 3

and so on...

Thanks :)

1
  • 6
    rsort($outcomes_array);. Commented May 26, 2011 at 14:33

6 Answers 6

15

Use rsort().

Sign up to request clarification or add additional context in comments.

Comments

9
rsort( $outcomes_array )

Note, it is not

$outcomes_array = rsort( $outcomes_array );

Comments

4
rsort( $outcomes_array );
print_r( $outcomes_array );

Comments

2
  • rsort is just for a numeric array
  • arsort is for an array with keys

Comments

1

As the default is SORT_REGULAR - compare items normally (don't change types) So the code should be:

$outcomes_array = array(1,4,2,3,5);
rsort( $outcomes_array, SORT_NUMERIC );//SORT_NUMERIC - compare items numerically
print_r( $outcomes_array );

Comments

0
$array = [2, 1, 22, 1, 3, 134, 3, 43, 23, 4];

function mi($arr){
    $count = count($arr);
    for ($j = 0; $j < $count; $j++) {
        $min = $arr[0];

        for ($i = 0; $i < count($arr); $i++) {
            if ($arr[$i] <= $min) {
                $min = $arr[$i];
            }
        }
        $ar[] = $min;

        for ($i = 0; $i < count($arr); $i++) {
            if ($arr[$i] == $min) {
                unset ($arr[$i]);
                $arr = array_values($arr);
                break;
            }
        }
    }
    return $ar;
 }
print_r(mi($array));

Comments

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.