1

Below is my array, I want to sort it:

$arr = array('0-3 months', '9-12 months', '3-6 months', '6-9 months', '12-18 months', '18-24 months');

It responds with sort function like :

Array
(
    [0] => 0-3 months
    [1] => 12-18 months
    [2] => 18-24 months
    [3] => 3-6 months
    [4] => 6-9 months
    [5] => 9-12 months
)

I want in below manner :

Array
(
    [0] => 0-3 months
    [1] => 3-6 months
    [2] => 6-9 months
    [3] => 9-12 months
    [4] => 12-18 months
    [5] => 18-24 months
)

Any solutions?

Thanks

2
  • 1
    Can it only be "x-y months" or are there other values? What about overlap? Etc. Commented Nov 19, 2014 at 6:36
  • 1
    Highly related question Commented Nov 19, 2014 at 6:38

4 Answers 4

4

You could use sort($arr, SORT_NUMERIC);. SORT_NUMERIC treats elements as numbers.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use natsort($arr); also

Comments

2

Have you tried SORT_NATURAL ?

sort($arr, SORT_NATURAL | SORT_FLAG_CASE);

source: php sort manual

Comments

1

Try

$arr = array('0-3 months', '9-12 months', '3-6 months', '6-9 months', '12-18 months', '18-24 months');
foreach($arr as $v) {
 $e = explode('-', $v);
 $n1[] = $e[0];
 $n = explode(' ', $e[1]);
 $n2[] = $n[0];
}
sort($n1);
sort($n2);
for($i=0; $i<count($n1); $i++) {
  $newarr[] = $n1[$i].'-'.$n2[$i].' '.'months';
}
print_r($newarr);

output:-

Array
(
    [0] => 0-3 months
    [1] => 3-6 months
    [2] => 6-9 months
    [3] => 9-12 months
    [4] => 12-18 months
    [5] => 18-24 months
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.