Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
);
like image 729
kamal Avatar asked Apr 09 '26 19:04

kamal


1 Answers

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.

Update for modern PHP versions, since create_function is deprecated:

uksort($array, function ($a, $b) { return -strnatcasecmp($a, $b); });

Update for PHP 7.4 with new syntax (not released as of writing):

uksort($array, fn($a, $b) => -strnatcasecmp($a, $b));
like image 80
TaZ Avatar answered Apr 12 '26 08:04

TaZ