Question

I have a array of strings:

0 - 5 50-100 10-50 150-250 100-150

Now I want to automatically sort these to:

0-5 10-50 50-100 100-150 150-250

How would I go about this?

Was it helpful?

Solution

You need to use the natsort() function. It sort numeric values "as a human being" :)

$input = array('0-5', '50-100', '10-50', '150-250', '100-150');
natsort($input);
print_r($input);

OTHER TIPS

http://www.php.net/manual/en/function.natsort.php Sort an array using a "natural order" algorithm

$a = array("0-5", "50-100", "10-50", "150-250", "100-150");
natsort($a);
print_r($a);

result:

Array
(
    [0] => 0-5
    [2] => 10-50
    [1] => 50-100
    [4] => 100-150
    [3] => 150-250
)

NOTE: the keys will stay the same and are not renumbered.

when this is not the desired result, you may want to renumber it yourself after the sort:

foreach ($a as $v)
    $new_a[] = $v;
$a = $new_a;

OR even better: (thx @liquorvicar)

$a = array_values( $a );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top