capsloc
capsloc

Reputation: 15

Sorting a flat array returns 1 instead of the modified array

I've been trying to use the sort() function to rearrange the array from smallest to largest.

This is my print_r of the array which came from serialized data that was imploded:

Array
    (
    [0] => 127173
    [1] => 127172
    [2] => 127174
    [3] => 127175
    [4] => 127178
    [5] => 127176
    [6] => 127177
    [7] => 127179
    [8] => 127180
    [9] => 127183
    [10] => 127181
)

With sort() and asort() I just get a 1 returning.

Upvotes: 0

Views: 113

Answers (2)

gastonmancini
gastonmancini

Reputation: 1102

Try this code... in fact the sort function is working fine.

$array = Array
    (
    '0' => 127173,
    '1' => 127172,
    '2' => 127174,
    '3' => 127175,
    '4' => 127178,
    '5' => 127176,
    '6' => 127177,
    '7' => 127179,
    '8' => 127180,
    '9' => 127183,
    '10' => 127181
    );

sort($array); // <= Sort the array desc

foreach( $array as $key => $value ){
    echo $key."\t=>\t".$value."\n";
}

Consider that sort function actually alters your array and returns bool. See doc.

Check this example online

Upvotes: 2

Ole Sauffaus
Ole Sauffaus

Reputation: 534

Use asort(), like this:

$A = Array (127173,127172,127174,127175,127178,127176,127177,127179,127180,127183,127181);
asort($A);
print_r($A);

Result:

Array ( [1] => 127172 [0] => 127173 [2] => 127174 [3] => 127175 [5] => 127176 [6] => 127177 [4] => 127178 [7] => 127179 [8] => 127180 [10] => 127181 [9] => 127183 )

Compare sorting-functions here: http://php.net/manual/en/array.sorting.php

Upvotes: 0

Related Questions