I'm look to naturally sort an array, in reverse order and not preserve the keys. For example, I'd like this array:
[0] => 1-string
[1] => 2-string
[2] => 10-string
[3] => 4-srting
[4] => 3-srting
To end up like this:
[0] => 10-srting
[1] => 4-string
[2] => 3-string
[3] => 2-string
[4] => 1-string
I've got it close with usort($array, 'strnatcmp'); but it's not in reverse order. array_reverse() after doesn't help.
Any ideas?
I'm a bit puzzled about "array_reverse() after doesn't help." because
<?php
echo PHP_VERSION, "\n";
$x = array(
'1-string',
'2-string',
'10-string',
'4-srting',
'3-srting'
);
natsort($x);
$x = array_reverse($x, false);
print_r($x);
prints
5.3.8
Array
(
[0] => 10-string
[1] => 4-srting
[2] => 3-srting
[3] => 2-string
[4] => 1-string
)
on my machine
Use the $preserveKeys
attribute of array_reverse()
to reset the keys as well as reversing the array after a natcasesort()
.
function rnatcasesort(&$array) {
natcasesort($array);
$array = array_reverse($array, false);
}
$values = array('1-string', '2-string', '10-string', '4-string', '3-string');
rnatcasesort($values);
var_dump($values);
/*
array(5) {
[0]=>
string(9) "10-string"
[1]=>
string(8) "4-string"
[2]=>
string(8) "3-string"
[3]=>
string(8) "2-string"
[4]=>
string(8) "1-string"
}
*/
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