Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort values from an array first based on another array

I want to sort values first depending on the order based on another array.

$countries = explode(',', 'AF,AL,DZ,AS,AD,FR,AO,AI,AQ,GB');
$popular   = explode(',', 'FR,GB');

I from $countries I want the values defined in $popular to form an array like this:

$ordered = ['GB,FR,AF,AL,DZ,AS,AD,AO,AI,AQ']

Thanks

like image 575
gold82 Avatar asked Apr 28 '26 05:04

gold82


1 Answers

You can use array_merge and array_diff

check working demo here : https://eval.in/873974

$countries = explode(',', 'AF,AL,DZ,AS,AD,FR,AO,AI,AQ,GB');
$popular   = explode(',', 'FR,GB');
sort($popular); // sort to manage order

// remove common element from $countries and merge with $popular
$ordered = array_merge($popular,array_diff($countries, $popular));     
echo "<pre>";
print_r($ordered);
like image 156
Jigar Shah Avatar answered Apr 29 '26 17:04

Jigar Shah