Hi there I have an annoying problem.

I have an array of values as follows:

Fashion 1
Fashion 5
Fashion 10
Fashion 3
Fashion 2
Fashion 4 etc

I want to sort them via alphabetical and numeric order so I used natsort however this gave the following result:

Fashion 1
Fashion 10
Fashion 2
Fashion 3
Fashion 4
Fashion 5 etc

But I want to display it as follows

Fashion 1
Fashion 2
Fashion 3
Fashion 4
Fashion 5
Fashion 6
Fashion 7
Fashion 8
Fashion 9
Fashion 10

i.e. like a human would order it numerically. I have read up and discovered that natsort has problems with spaces and underscores so was wondering if anyone knew a work around to order things naturally (preferably without removing the spaces from the entries, but if necessary they can be remove then re-added after.

Thanks for your help,
Bob

    [man]natsort/man worked fine for me, and gave identical results to using usort($array, 'strnatcmp'). Maybe a PHP version issue? (I tested using PHP 5.2.4 -- yeah, a bit old, but close to what my hosting company uses. :rolleyes: )

    <pre><?php
    $test1 = $test2 = array(
       'Fashion 1',
       'Fashion 5',
       'Fashion 10',
       'Fashion 3',
       'Fashion 2',
       'Fashion 4'
    );
    ?>UNSORTED:
    <?php
    print_r($test1);
    print_r($test2);
    ?>
    SORTED:
    <?php
    natsort($test1);
    usort($test2, 'strnatcmp');
    print_r($test1);
    print_r($test2);
    ?></pre>
    

    Output:

    UNSORTED:
    Array
    (
        [0] => Fashion 1
        [1] => Fashion 5
        [2] => Fashion 10
        [3] => Fashion 3
        [4] => Fashion 2
        [5] => Fashion 4
    )
    Array
    (
        [0] => Fashion 1
        [1] => Fashion 5
        [2] => Fashion 10
        [3] => Fashion 3
        [4] => Fashion 2
        [5] => Fashion 4
    )
    SORTED:
    Array
    (
        [0] => Fashion 1
        [4] => Fashion 2
        [3] => Fashion 3
        [5] => Fashion 4
        [1] => Fashion 5
        [2] => Fashion 10
    )
    Array
    (
        [0] => Fashion 1
        [1] => Fashion 2
        [2] => Fashion 3
        [3] => Fashion 4
        [4] => Fashion 5
        [5] => Fashion 10
    )
    

    PS: Don't forget [man]natcasesor/man if you need the sorting to be case-insensitive.

      Thanks so much for the replies, Undrium's solution worked, not sure why the natsort was not working, all part of the fun of web design i guess.

      Cheers,
      Bob

        Write a Reply...