1

I can't sort my array so that numbers comes before - (hyphen).

My array today:

Array
(
    [-] => Test
    [0] => Test
    [1] => Test
    [2] => Test
)

The order I want:

Array
(

    [0] => Test
    [1] => Test
    [2] => Test
    [-] => Test
)

I have searched both here and on Google. But found no answers. I have tried experimenting with ksort() and usort(), but without success.

3 Answers 3

4

You could create your own compare function with uksort which handels such special cases.

uksort($a, function($a, $b) {
   if (is_numeric($a) && is_numeric($b)) return $a - $b;
   else if (is_numeric($a)) return -1;
   else if (is_numeric($b)) return 1;
   return strcmp($a, $b);
});
Sign up to request clarification or add additional context in comments.

Comments

4

Use natural order sorting function

natsort()

example:

$arr = ['_', 6, 3, 5];
natsort($arr);
print_r($arr);

output:

Array
(
    [2] => 3
    [3] => 5
    [1] => 6
    [0] => _
)

If you want to sort by keys then you can use ksort() function with flag SORT_NATURAL ksort($arr, SORT_NATURAL);

example:

$arr = [
   '_' => 'test',
    6  => 'test', 
    3  => 'test', 
    5  => 'test'
];

ksort($arr, SORT_NATURAL);

1 Comment

so he can use ksort with flag SORT_NATURAL
0

function check($x, $y){
if(is_numeric($x) && !is_numeric($y))
return 1;
else if(!is_numeric($x) && is_numeric($y))
return -1;
else
return ($x < $y) ? -1 : 1;
}
$array = array("-", "1", "2", "3");
usort ( $array , 'check' );

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.