Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sort array alphabetically then numerically?

I have an array of values which are either all-letters or all-numbers and need to sort them in an ascending fashion. Additionally, I want all-numeric values to be moved to the end of the array so that they occur after all of the non-numeric values.

$test = ["def", "yz", "abc", "jkl", "123", "789", "stu"];

If I run sort() on it I get:

Array
(
    [0] => 123
    [1] => 789
    [2] => abc
    [3] => def
    [4] => jkl
    [5] => stu
    [6] => yz
)

but I'd like to see:

Array
(
    [0] => abc
    [1] => def
    [2] => jkl
    [3] => stu
    [4] => yz
    [5] => 123
    [6] => 789
)

I tried array_reverse(), but that didn't seem to change anything. I'm at a loss for how to get the numbers last, but in ascending order.

like image 826
chris Avatar asked Sep 25 '12 19:09

chris


3 Answers

What you need is sort but with a custom comparison function (usort). The following code will get it done:

function myComparison($a, $b){
    if(is_numeric($a) && !is_numeric($b))
        return 1;
    else if(!is_numeric($a) && is_numeric($b))
        return -1;
    else
        return ($a < $b) ? -1 : 1;
} 
$test = array("def", "yz", "abc", "jkl", "123", "789", "stu");
usort ( $test , 'myComparison' );
like image 194
DiverseAndRemote.com Avatar answered Nov 20 '22 12:11

DiverseAndRemote.com


You could convert your numbers to integers before sorting:

$array = array("def", "yz", "abc", "jkl", "123", "789", "stu");

foreach ($array as $key => $value) {
    if (ctype_digit($value)) {
        $array[$key] = intval($value);
    }
}

sort($array);
print_r($array);

Output:

Array
(
  [0] => abc
  [1] => def
  [2] => jkl
  [3] => stu
  [4] => yz
  [5] => 123
  [6] => 789
)
like image 24
Tchoupi Avatar answered Nov 20 '22 13:11

Tchoupi


In the following code is separate the data in two arrays: one is numerical the other is not and sort it and merge it.

$arr1 = $arr2 = array();

$foreach ($arr as $val) {

if (is_numeric($val)) {array_push($arr2, $val); } 
else {array_push($arr1, $val);}

} 

so you have to separate arrays whit numeric and non-numeric

sort($arr2);
sort($arr1);

$test = array_merge($arr2,$arr1);
like image 2
faq Avatar answered Nov 20 '22 14:11

faq