kamal kamal - 3 months ago 10
PHP Question

sort array by keys and reverse the result

I have a array like this:

$array = array(
[1]=>'something',
[0.2]=>'something',
[0.1]=>'something',
[0.3]=>'something',
[0.10]=>'something'
);


Now i like to sort this array by key, so for that i am using this code:

uksort($array, 'strnatcasecmp');


The above code works fine, but the only problem is that i want to reverse the result.
For this purpose i used
krsort
,
array_reverse
,
rsort
after
uksort
, but all of them change
uksort
's result.

So have can i sort this array by key in natural order and reverse the result?

What i want should be like :

$array = array(
[1]=>'something',
[0.10]=>'something',
[0.3]=>'something',
[0.2]=>'something',
[0.1]=>'something'
);

TaZ TaZ
Answer

Try this:

uksort($array, create_function('$a,$b', 'return -strnatcasecmp($a,$b);'));

Since you already use a variant of uksort (user-function defined sort), this version just reverses the order by inverting the result of the comparison function. I think it should work for you.

Alternatively try this:

uksort($array, 'strnatcasecmp');
$array = array_reverse($array, true);

Note the true parameter, that preserves your keys.