Reputation: 68720
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?
Upvotes: 0
Views: 1089
Reputation: 4524
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];
}
Upvotes: 2
Reputation: 1240
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];
Upvotes: 1