phparrayssortingcustom-sort

Sort an array by another array of value priorities which may have more values than the original input array


I have a comma separated string/array:

$input = "facebook,steam,tumblr,email,instagram,twitter,twitch,youtube,pinterest,amazon,disqus";
$input = explode(",", $input);

that I want to be ordered based on another array:

$order = "email,facebook,instagram,twitter,twitch,youtube,steam,pinterest,tumblr,amazon,disqus";
$order = explode(",", $order);

$input will always contain a value that is in $order and I want it to be sorted based on the order that it comes in $order. This is a bit tricky because $input will only contain a subset of values from $order.

For example, an input of twitter,twitch,email,facebook would return email,facebook,twitter,twitch


I have already found This Solution but it does not apply because I am not dealing with keys in my array.


Solution

  • No need to do any fancy sorting algorithms. You can just do:

    array_intersect($order, $input);

    This will return an array containing all the values of $order that are present $input. And thankfully this function keeps the original order in $order.


    Note: The order of the arguments to array_intersect() is important. Make sure you pass in $order first, since that is your reference array, then pass in $input, just like in the example above. Otherwise it will do the opposite, which is not what you want.

    More info: http://php.net/manual/en/function.array-intersect.php