Magento 2 – Get Country Code from Country Name

factorymagento2

I have the country name with me. How can I get corresponding country code from it.
For ex: If the country name is Unites States, I want to get country code from it ie, US

If there any way for it?

I found many useful links for getting country name from country code. I want it in the reverse manner.

   public function __construct(
            \Magento\Directory\Model\CountryFactory $countryFactory
        ) {
            $this->_countryFactory = $countryFactory;
        }

    public function getCountryname($countryCode){    
        $country = $this->_countryFactory->create()->loadByCode($countryCode)
        echo $country->getName();
    }

Best Answer

You forgot to add semicolon after $country = $this->_countryFactory->create()->loadByCode($countryCode)

Add code in your controller :

protected $_country;

public function __construct(
    \Magento\Directory\Model\Country $country
) {
    $this->_country = $country;
}

public function getCountryname() {
    $countryName = "Your country name";
    $countryCollection = $this->_country->getCollection();
    foreach ($countryCollection as $country) {
       if ($countryName == $country->getName()) {
          $countryId = $country->getCountryId();
          break;
       }
    }
    echo $countryId;
}

remove generated folder and clean cache.