Sorting an associative array in custom order
This short note shows how you can sort an associative array using another array as order map.
For example, let's take the following problem. There is an array with translations and we need to sort them in the desired order:
$languages = [ 'fr' => 'French', 'ru' => 'Russian', 'en' => 'English' ]; $order = [ 'ru', 'en', 'fr', 'es' ]; // desired order
$order = array_flip( $order ); $order = array_intersect_key( $order, $languages ); // remove from $order what isn't in $languages // sort $languages = array_merge( $order, $languages ); // or $languages = array_replace( $order, $languages );
print_r( $languages ); /* Array ( [ru] => Russian [en] => English [fr] => French ) */