简体   繁体   中英

Convert country code to country name

I want to convert a country's ISO code to its name using the following function:

function convertcodes($in, $type){
    $out = "";
    $long = array('Afghanistan' , 'Åland Islands' , 'Albania' , 'Algeria' , 'American Samoa' , 'Andorra');
    $short = array('af','ax','al','dz','as','ad');
    $in = trim($in);
    switch($type){
        case 'long':
            $out = str_replace($short, $long, $in);
        break;
        case 'short':
            $out = str_replace($long, $short, $in);
        break;
    }
return $out;
}

The problem is that it returns ALL countries instead of the one that I'm looking for because its matching strings. How can I make it match the exact string? Using preg_replace won't work with an array.

(Obviously the actual arrays are much longer, I stripped a part here in order to not make my posted code too long.)

I would use a indexed array instead.

As example:

$array = [
    "af" => "Afghanistan",
    "ax" => "Åland Islands",
    // ... and so on
];

This way you could use the given shortname to retrieve the long name or vise versa.

Example for retrieve:

echo $array['af'] // returns Afghanistan
// or
echo array_search ("Afghanistan", $array) // returns af

You can easily convert your both already existing arrays into one using this code snipped (thanks to @splash58 ):

$array = array_combine($short, $long);

Ionic 's solution is fine and probably the best but if you need two arrays, please consider the following one

function convertcodes($in, $type){
    $result = false;
    $long = array('Afghanistan' , 'Åland Islands' , 'Albania' , 'Algeria' , 'American Samoa' , 'Andorra');
    $short = array('af','ax','al','dz','as','ad');
    $in = trim($in);
    switch($type){
        case 'long':
            $index = array_search($in, $long);
            if ($index !== false) {
                $result = $short[$index];
            }
        break;
        case 'short':
            $index = array_search($in, $short);
            if ($index !== false) {
                $result = $long[$index];
            }
        break;
    }
    return $result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM