Question

Depending on the user's country, I want to load the flag image for the country thats stored in an array. Currently I only know the switch method, like so:

$countryFlags = array("afghanistan.png", "albania.png", "algeria.png", "andorra.png" ... );

// gets the user country from DB
$userCountry = $country['Country'];

switch($userCountry) {
    case "Australia":
        echo /* the image name from countryFlags array */ ; break;
    case "America":
        echo /* the image name from countryFlags array */ ; break;
    default:
        echo("Unknown");
}

.. but it'll take a while to write the conditions and I believe there must be a better way to do it?

Was it helpful?

Solution 2

Create an array with the country code as key, and the image URL as value:

$countryFlags = array();
$countryFlags['za'] = images/za.png;
$countryFlags['us'] = images/us.png;
// etc...

echo $countryFlags[$userCountryCode];

OTHER TIPS

Assuming you have control over the naming why not simply:

$userCountry = $country['Country'];

echo strtolower($userCountry) . ".png";

Giving it "America" in the commandline would provide america.png return.

If you can't do that construct your array as follows:

$countryFlags = array(
  "America" => "america.png",
  "Afganistan" => "afganistan.png",
  ...etc...
);

echo $countryFlags[$userCountry];

EDIT::

A mix & match of the above two

//Define list of countries that aren't a direct translation
$countryFlags = array(
  "Canada" => "cdn_flag.png",
  "Mexico" => "mexico.jpg",
);

if ( !in_array($userCountry,$countryFlags) ) {
  echo strtolower($userCountry) . ".png";
} else {
   echo $countryFlags[$userCountry];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top