WordPress at Your Fingertips

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

Now, we need to sort $languages array elements by the order in $order array. It can be done by using the array_merge() or array_replace() functions.

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

Get:

print_r( $languages );
/*
Array
(
	[ru] => Russian
	[en] => English
	[fr] => French
)
*/
No comments
    Log In