Bijan Bijan - 1 year ago 109
PHP Question

Order Array Based on Other 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);

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

For example, an input of
would return

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

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download