Get country code from country name in Magento

Its very simple to get the country name by given country code with following code,

$country_name=Mage::app()->getLocale()->getCountryTranslation("in");
or
$countryName = Mage::getModel("directory/country")->load("in")->getName();

But in one of the application I come across the situation where I need get country code from country name. I have used bellow logic to fulfill my need,

$countryList = Mage::getResourceModel('directory/country_collection')
                    ->loadData()
                    ->toOptionArray(false);
$needle = "India";
foreach ($countryList as $key => $val) 
{
   if (strtolower($val['label']) === strtolower($needle)) {
       echo $val['value'];
       break;
   }
}

You will get the array of all country list with in $countryList variable. From that array I am searching for my required country code.

I am sure there must be some alternate way to get the same. If you know some alternate way, which is more convenient you are most welcome to post your ideas or suggestions.

Advertisements

2 thoughts on “Get country code from country name in Magento

  1. Pingback: Get country code from country name in Magento | Kenneth Carnesi

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s