Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Natural sorting of PHP array in reverse and not preserving keys

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?

like image 260
Phil Avatar asked Mar 23 '12 16:03

Phil


2 Answers

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

like image 162
VolkerK Avatar answered Sep 30 '22 01:09

VolkerK


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"
}
*/

like image 27
Andrew Moore Avatar answered Sep 30 '22 01:09

Andrew Moore