Saad Bashir
Saad Bashir

Reputation: 4519

PHP Sorting Array ASC

I am trying to Sort the following Array but for some odd reason it doesn't seem to work

$sizearray = Array ( 
                       [0] => 39 
                       [1] => 40 
                       [2] => 41 
                       [3] => 42 
                       [4] => 43 
                       [5] => 44 
                       [6] => 45 
                       [7] => 39 
                       [8] => 40 
                       [9] => 41 
                       [10] => 42 
                       [11] => 43 
                       [12] => 44 
                       [13] => 45 
                       [14] => 39 
                       [15] => >40 
                       [16] => 41 
                       [17] => 42 
                       [18] => 43 
                       [19] => 44 
                       [20] => 45 
                 );


$sizearray = array_values(sort(array_unique($sizearray)));

And the following warnings shows up:

>Warning: array_values() [function.array-values]: The argument should be an array in 
>/home/starlet/public_html/productlist.php on line 349

Note: If i remove sort() function, the array_values() function runs fine.

Upvotes: 0

Views: 608

Answers (3)

Motilal Soni
Motilal Soni

Reputation: 366

<?php

$fruits = array(
    "Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

From the docs:

Return Values

Returns TRUE on success or FALSE on failure.

Note how it does not say "Returns the sorted array". This is because sort() sorts in-place.

Upvotes: 1

Adam Wagner
Adam Wagner

Reputation: 16107

That's because sort is in-place and returns a boolean.

From the docs:

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

You'll probably need to do something like this:

$sizearray = array_unique($sizearray);
sort($sizearray);
$sizearray = array_values($sizearray);

Upvotes: 2

Related Questions