phparrayssortingusortcustom-sort

Sort flat array with a known set of possible values in a custom order


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

For example I got an array containing:

['south', 'west', 'north']

Now I would like to sort the array in a custom order like: north, then east, then south, then west.

So in my example the values should be in this order:

['north', 'south', 'west']

How can I do that?


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 ) );