I've been cracking my brain trying to solve this challenge.
PHP default sort
function doesn't provide the solution but still, using usort
isn't easy either.
So this is what I'm trying to solve. I created an array in this order:
$data = array( '_', '@', ...range(-10, 10), ...range('A', 'Z'), ...range('a', 'z') )
Now I want to sort this array using usort
so that:
negative
numbers come first,uppercase
letters comes next_
&@
characters followslowercase
letters follows- Then finally
positive
numbers ends the order
Somewhat like:
/*
array(
"-10",
"-9",...
"A",
"B",...
"_",
"@", // @ may come first
"a",
"b",...
"1",
"2"...
) */
Is there any method available to solve this?
What I tried?
usort($data, function($a,$b) {
if( is_numeric($a) && (int)$a < 0 ) return -1; // take negative number to start
else {
if( !is_numeric($a) ) {
if( is_numeric($b) && (int)$b > 0 ) return -1;
else return $b < $a ? 1 : 0;
} else return 1; // take positive number to end
}
});