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'
);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With