-2

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

3
  • same index of short correspond to same index of long, right? Commented Jun 21, 2015 at 10:42
  • Yes, no problem there. Commented Jun 21, 2015 at 10:44
  • Why not just use a map instead? Commented Jun 21, 2015 at 10:44

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

4 Comments

@Sander you make convert your 2 array in such one by $array = array_combine($short, $long);
Yes, @splash58 is right. But If I'm right, both arrays need the right order and length. :-)
This logic is due to the question
Yes sure. Is it ok for you if I add those part of the comment to my answer?
1

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

1 Comment

I gave you an upvote, cause if someone really needs both arrays this would work for him too. :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.