How to Sort an Array by Keys Based on Order in a Secondary Array in PHP?

Imagine you had an array like the following:

// original array
$user = [
	'age' => 45, 
	'email' => 'john@doe.com', 
	'last_login' => '2016-10-21', 
	'name' => 'John Doe'
];

And you wanted to sort its keys based on a custom sort order supplied in another array, for example:

// sort order we want
$order = ['name', 'email', 'age', 'last_login'];

Based on which, you would expect the following result:

/* output: Array(
    'name' => 'John Doe',
    'email' => 'john@doe.com',
    'age' => 45,
    'last_login' => '2016-10-21'
); */

To achieve that, you can use any of the following methods:

#Using array_merge()

// PHP 4+
$ordered_array = array_merge(array_flip($order), $user);

Description:

  1. array_flip() changes the $order array's values to keys;
  2. Using array_merge(), since both the arrays have same keys, the values of the first array is overwritten by the second array, whilst the order of keys of the first one is maintained.

#Using array_replace()

// PHP 5+
$ordered_array = array_replace(array_flip($order), $user);

Description:

  1. array_flip() changes the $order array's values to keys;
  2. array_replace() replaces the values of the first array with values having the same keys in the second array.

#Using uksort()

// PHP 4+
uksort($user, function($key1, $key2) use ($order) {
	return ((array_search($key1, $order) > array_search($key2, $order)) ? 1 : -1);
});

Description:

  1. uksort() allows us to sort an array by keys using a user-defined comparison function that is called multiple times, every time with two keys (in our case, from the $user array);
  2. The result of our custom sort function must return 0 if both items are same, a positive integer if $key1 is greater than $key2 and a negative integer if $key1 is less than $key2.

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.