Question

I have an array that contain the values north, east, south or west.

For example I got an array with the values in this order: south, west and north.

Now I would like to sort the array like north, east, south and west.

So in my example the values should be in this order: north, south, west.

How can I do that?

Thanks!

Was it helpful?

Solution

You could also use array_intersect(). It preserves the order of the first array. Give an array of all cardinal directions in the correct order as the first parameter and the array to sort as the second.

$cardinals = array( 'north', 'east', 'south', 'west' );
$input = array( 'south', 'west', 'north' );

print_r( array_intersect( $cardinals, $input ) );

OTHER TIPS

You could do something along the lines of this (I believe it's what Samuel Lopez is also suggesting in the comments):

$arr = array ('north', 'west', 'south', 'east', );

function compass_sort ($a, $b)
{
        $cmptable = array_flip (array (
                'north',
                /* you might want to add 'northeast' here*/
                'east',
                /* and 'southeast' here */
                'south',
                'west',
        ));

        $v1 = trim (mb_strtolower ($a));
        $v2 = trim (mb_strtolower ($b));

        if ( ! isset ($cmptable[$v1])
           || ! isset ($cmptable[$v2]))
        {
                /* error, no such direction */
        }

        return $cmptable[$v1] > $cmptable[$v2];
}

usort ($arr, 'compass_sort');

This assigns a number to each direction and sorts on that number, north will be assigned zero, east one (unless you add something in between) etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top