Sander Sander - 1 year ago 99
PHP Question

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);
case 'long':
$out = str_replace($short, $long, $in);
case 'short':
$out = str_replace($long, $short, $in);
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.)

Answer Source

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