Sort array based on another array

Take one array as your order:

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

You can sort another array based on values using array_intersect­Docs:

/* sort by value: */
$array = array('south', 'west', 'north');
$sorted = array_intersect($order, $array);
print_r($sorted);

Or in your case, to sort by keys, use array_intersect_key­Docs:

/* sort by key: */
$array = array_flip($array);
$sorted = array_intersect_key(array_flip($order), $array);
print_r($sorted);

Both functions will keep the order of the first parameter and will only return the values (or keys) from the second array.

So for these two standard cases you don’t need to write a function on your own to perform the sorting/re-arranging.

Leave a comment