Sort values from an array first based on another array

Viewed 46

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

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

try this code

<?php 
        $arr= array();
        $countries = explode(',', 'AF,AL,DZ,AS,AD,FR,AO,AI,AQ,GB');
        $popular   = explode(',', 'FR,GB');
        $total_popular = count($popular);
        $total_countries = count($countries);

        for ($i=0; $i < $total_popular; $i++) { 
            if (in_array($popular[$i], $countries)) {
                $arr[]=$popular[$i];
            }
        }
        for ($j=0; $j < $total_countries; $j++) { 
            if (! in_array($countries[$j], $arr)) {
                $arr[]=$countries[$j];
            }
        }
        echo "<pre>";
        print_r($arr);

        ?>

Your desired output of this code is

enter image description here

Related